Python-如何使用%s修改文本输出?

Python-如何使用%s修改文本输出?,python,string,Python,String,很简单,但如何修改%s的输出值 print "Successfully created the file: %s" % iFile + '.txt' print "Successfully created the file: %s" % (iFile + '.txt') 我尝试过使用的,{},但没有任何效果 iFile是文件的名称,我希望在显示文件时,在文件末尾显示.txt 编辑: 我获得了成功创建文件的输出:.txt使用: 例如: In [1]: iFile = "foo" In [2]

很简单,但如何修改%s的输出值

print "Successfully created the file: %s" % iFile + '.txt'
print "Successfully created the file: %s" % (iFile + '.txt')
我尝试过使用的,{},但没有任何效果

iFile是文件的名称,我希望在显示文件时,在文件末尾显示.txt

编辑:

我获得了成功创建文件的输出:.txt

使用:

例如:

In [1]: iFile = "foo"

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

由于您似乎有一个文件,而不是文件名,因此可以执行以下操作:

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'
请注意,现在的输出是foo.txt.txt,具有双扩展名。如果由于文件名已经是foo.txt而不需要此扩展名,则不应打印其他扩展名


使用%是格式化字符串的旧方法。当前的。

问题在于,您没有向它传递一个带有文件名的字符串,而是向它传递一个文件句柄对象,这是完全不同的。要从文件句柄中获取名称,请使用iFile.name


这将打印您要查找的内容。

您可以尝试以下代码。我在pythonshell中进行了尝试,效果很好。我想你只是漏掉了括号

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

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