在 Python 中打开多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12914682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
opening multiple files in Python
提问by Dinna Lee
How can I open many files at same time in the python programming language to run my program?
如何用python编程语言同时打开多个文件来运行我的程序?
I have about 15 files, just now I have worked with one of them like below:
我有大约 15 个文件,现在我已经使用了其中一个文件,如下所示:
f=open("Exemplo_1.txt","rU")
回答by venkatKA
f1=open("Exemplo_1.txt","rU");
f2=open("Exemplo_2.txt","rU");
...
f15=open("Exemplo_15.txt","rU");
You're basically creating File objects to get access to the files.
您基本上是在创建 File 对象来访问文件。
回答by hughdbrown
I'd do something like this:
我会做这样的事情:
try:
f = [open("Exemplo_%d.txt" % i, "rU") for i in range(1, 16)]
# do stuff
finally:
for fh in f:
fh.close()
See try/finally.
请参阅try/finally。
回答by iruvar
if you need to loop over multiple files at one shot, use the fileinput module
如果您需要一次遍历多个文件,请使用 fileinput 模块
for x in fileinput.input(['patterns.in', 'logfile.txt']):
print x
回答by Jon Clements
You could use a combination of globand fileinput
你可以使用的组合glob和fileinput
import fileinput
from glob import glob
fnames = glob('Exemplo_*.txt')
for line in fileinput.input(fnames):
pass # do whatever

