读取目录中的所有文件内容

2024-04-18 15:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有目录poem,其中包含50个文件,我想全部读取它们。

for file in os.listdir("/home/ubuntu/Desktop/temp/poem"):
    print file
    f = open(file, 'r')
    print f.read()
    f.close()

此代码读取目录中所有文件的文件名。 但它失败了

f = open(file, 'r')

IOError: [Errno 2] No such file or directory: '32'

Tags: 文件in目录homeforreadosubuntu
2条回答

os.listdir只返回文件名,要获取将该文件名与正在读取的文件夹连接所需的完整路径:

folder = "/home/ubuntu/Desktop/temp/poem"
for file in os.listdir(folder):
    print file
    filepath = os.path.join(folder, file)
    f = open(filepath, 'r')
    print f.read()
    f.close()

您正在使用目录文件夹搜索当前联接文件路径中的文件。

import os

for i in os.listdir("/home/ubuntu/Desktop/temp/poem"):
    if os.path.isfile(os.path.join("/home/ubuntu/Desktop/temp/poem",i)):
        print os.path.join("/home/ubuntu/Desktop/temp/poem",i)
        f=open(os.path.join("/home/ubuntu/Desktop/temp/poem",i),"r")
        print f.readlines()
        f.close()

相关问题 更多 >