如何打开文件列表中的每个文件,对文件执行某些操作然后转到下一个文件?
我有一个包含1000个文本文件的目录。我已经创建了一个包含所有文件名的列表,现在我想逐个文件打开。有人知道怎么做吗?
到目前为止我所拥有的:
from os import listdir
from os.path import isfile, join
files_in_dir = [ f for f in listdir('nes') if isfile(join('nes',f)) ]
if f.endswith(".txt"):
print(f)
答案 0 :(得分:1)
from os import listdir
from os.path import isfile, join
files_in_dir = [ f for f in listdir('nes') if isfile(join('nes',f)) ]
for f in files_in_dir:
if f.endswith(".txt"):
with open(f, 'r') as in_file:
for line in in_file:
# Here you have access to lines of the opened file.
答案 1 :(得分:0)
无需创建单独的列表来保存文件名。只需直接迭代listdir()
的结果。
for fname in listdir('nes'):
fname = join('nes', fname)
if fname.endswith('.txt') and isfile(fname):
with open(fname, 'r') as f:
# do something with open file f