使用os模块从文件夹中读取文件

问题描述 投票:1回答:1

对于模式识别应用程序,我想使用os模块从另一个文件夹中读取和操作jpeg文件。

我试图使用str(文件)和file.encode('latin-1'),但他们都给我错误

我试过了 :

allLines = []

path = 'results/'
fileList = os.listdir(path)
for file in fileList:
   file = open(os.path.join('results/'+ str(file.encode('latin-1'))), 'r')
   allLines.append(file.read())
print(allLines)

但我得到一个错误说:没有这样的文件或目录“results / b'thefilename”

当我希望列表中包含可访问的所需文件名时

python
1个回答
1
投票

如果您可以使用Python 3.4或更高版本,则可以使用pathlib module来处理路径。

from pathlib import Path

all_lines = []
path = Path('results/')
for file in path.iterdir():
    with file.open() as f:
        all_lines.append(f.read())
print(all_lines)

通过使用with语句,您不必手动关闭文件描述符(当前缺少的文件描述符),即使在某个时刻引发了异常。

© www.soinside.com 2019 - 2024. All rights reserved.