我想从目录中读取所有文件,并将文件名和内容都导入到列表中。我编写了以下代码,但它只导入目录中的最后一个文件。
import os
fileList = []
for dirname, dirnames, filenames in os.walk('.'):
for filename in filenames:
file = os.path.join(dirname, filename)
f = open(file, 'r')
contents = f.read()
newItem = (file, contents)
fileList.append(newItem)
print(fileList)
答案 0 :(得分:0)
似乎是缩进的问题。试试这个:
import os
fileList = []
for dirname, dirnames, filenames in os.walk('.'):
for filename in filenames:
file = os.path.join(dirname, filename)
f = open(file, 'r')
contents = f.read()
newItem = (file, contents)
fileList.append(newItem)
print(fileList)
此外,您还没有关闭程序中不是好风格的文件。最好使用一个处理打开和关闭文件的所谓上下文管理器:
import os
fileList = []
for dirname, dirnames, filenames in os.walk('.'):
for filename in filenames:
file = os.path.join(dirname, filename)
with open(file, 'r') as f:
contents = f.read()
newItem = (file, contents)
fileList.append(newItem)
print(fileList)