对于模式识别应用程序,我想使用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 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
语句,您不必手动关闭文件描述符(当前缺少的文件描述符),即使在某个时刻引发了异常。