如何遍历文件列表并打开每个文件

时间:2019-07-04 00:03:31

标签: python text operating-system

我有一个文件名列表,我试图遍历每个文件并使用with open语句。

      #list of text files 
      files = ['file1.txt','file2.txt','file3.txt']
      for file in files: 
          with open(file as f ): 
             file.readlines()

2 个答案:

答案 0 :(得分:1)

with open(file as f )应该更改为with open(file, 'r') as f。这指定我们要在读取模式下打开文件对象,并在读取模式下将该文件对象存储为变量f

答案 1 :(得分:1)

这应该有效。请注意,我使用os.chdir()将工作目录更改为包含文件的目录。如果您的文件列表包含文件的完整路径,则无需这样做。

import os
#change working directory to the directory containing the files
os.chdir("C:\\Folder1\\Folder Containing files")
files = ['file1.txt','file2.txt','file3.txt']
content = []
for file in files: 
    with open(file, 'r') as f:
        content.append(f.readlines()) # note that it's f.readlines() and not file.readlines()