文件名号为1-32的东西,我想按顺序打开它们,如:
i = 1
while i < 32:
filename = "C:\\Documents and Settings\\file[i].txt"
f = open(filename, 'r')
text = f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)
但这会查找文件"file [i] .txt"而不是file1.txt,file2.txt等等.我如何使变量成为双引号内的变量?是的,我知道它没有缩进,请不要认为我是愚蠢的.
我认为这可能有用:构建文件名就像你构建包含变量的任何其他字符串一样:
filename = "C:\\Documents and Settings\\file" + str( i ) + ".txt"
Run Code Online (Sandbox Code Playgroud)
或者如果您需要更多选项来格式化数字:
filename = "C:\\Documents and Settings\\file%d.txt" % i
Run Code Online (Sandbox Code Playgroud)