-1

pretty straight forward to you guys but how do you modify the values output from the %s?

print "Successfully created the file: %s" % iFile + '.txt'

I have tried using ()'s, {}'s, but nothing is working?

iFile is the name of the file and I want it to be displayed with .txt at the end when its displayed.

Edit:

I get the output Successfully created the file: <open file 'test', mode 'rb' at 0x14cef60>.txt

Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
Eric1989
  • 619
  • 3
  • 9
  • 17

3 Answers3

7

Use str.format(*args, **kwargs:

"Successfully created the file: {0}.txt".format(iFile)

Example:

In [1]: iFile = "foo"

In [2]: "Successfully created the file: {0}.txt".format(iFile)
Out[2]: 'Successfully created the file: foo.txt'

Edit

Since you seem to have a file, not a file name, you could do this:

In [4]: iFile = open("/tmp/foo.txt", "w")

In [5]: "Successfully created the file: {0}.txt".format(iFile)
Out[5]: "Successfully created the file: <_io.TextIOWrapper name='/tmp/foo.txt' mode='w' encoding='UTF-8'>.txt"

In [6]: "Successfully created the file: {0}.txt".format(iFile.name)
Out[6]: 'Successfully created the file: /tmp/foo.txt.txt'

Note that now the output is foo.txt.txt with a double extension. If you don't want this because the name of the file already is foo.txt, you don't should print the additional extension.


Using % is the old way to format strings. The current Python tutorial explains format in detail.

4

The problem is that you're not passing it a string with the file name - you're passing it a file handle object, which is totally different. To get a name out of a file handle, use iFile.name.

print "Successfully created the file: %s" % iFile.name + '.txt'

That will print what you're looking for.

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
-1

you can try the following code. I tried in in Python shell and it works. I think you were just missing the parentheses.

print "Successfully created the file: %s.txt" % iFile

or

print "Successfully created the file: %s" % (iFile + '.txt')
Mohamed Termoul
  • 369
  • 2
  • 13