如何在变量作为文件名的一部分打开python中的文件?

Aru*_*osh 7 python python-2.7 python-3.x

文件名号为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)

ale*_*cxe 5

您已经提供了答案。顺便说一句,使用with上下文管理器而不是手动调用close()

i = 1
while i < 32:
    filename = "C:\\Documents and Settings\\file%d.txt" % i
    with open(filename, 'r') as f:
        print(f.read())
Run Code Online (Sandbox Code Playgroud)


Jas*_*ont 5

首先,将循环更改为,while i <= 32否则将排除名称中包含 32 的文件。你的第二个选择filename = "C:\\Documents and Settings\\file%d.txt" % i应该有效。

如果文件中的数字是 0 填充的,例如“file01.txt”、“file02.txt”,则可以使用%.2d代替普通的 %d