非常直接给你们,但你如何修改%s的输出值?
print "Successfully created the file: %s" % iFile + '.txt'
Run Code Online (Sandbox Code Playgroud)
我尝试使用()的,{}的,但没有什么工作?
iFile是文件的名称,我希望它在显示时以.txt显示.
编辑:
我得到了输出 Successfully created the file: <open file 'test', mode 'rb' at 0x14cef60>.txt
小智 7
"Successfully created the file: {0}.txt".format(iFile)
Run Code Online (Sandbox Code Playgroud)
例:
In [1]: iFile = "foo"
In [2]: "Successfully created the file: {0}.txt".format(iFile)
Out[2]: 'Successfully created the file: foo.txt'
Run Code Online (Sandbox Code Playgroud)
编辑
由于您似乎有一个文件,而不是文件名,您可以这样做:
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'
Run Code Online (Sandbox Code Playgroud)
请注意,现在输出foo.txt.txt具有双扩展名.如果您不希望这样,因为文件的名称已经存在foo.txt,则不应打印其他扩展名.
使用%是格式化字符串的旧方法.当前的Python教程format详细解释.