从目录打开文件,并保留文件名和内容

时间:2017-04-14 17:08:05

标签: python python-3.x file python-3.6

我想从目录中读取所有文件,并将文件名和内容都导入到列表中。我编写了以下代码,但它只导入目录中的最后一个文件。

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)

1 个答案:

答案 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)