我有一个txt文件夹,我想把它作为一个变量导入到python中。理想情况下,我需要一个变量'profession_texts‘,其中每个txt文件都是列表中的一个元素。这是我目前所拥有的:
import os
profession_folder_path = '../fp/Updated/Profession/'
profession_files = os.listdir(profession_folder_path)
profession_texts = [open(profession_folder_path+file_name, encoding='utf-8').read() for file_name in profession_files]
print(profession_texts[0])PermissionError: [Errno 13] Permission denied: '../fp/Updated/Profession/Athlete'所以我有两个问题。我如何摆脱这个PermissionError?一旦解决了这个错误,我的代码能实现我的目标吗?
发布于 2017-04-16 12:20:49
您无需将文件名与目录一起附加为(profession_folder_path+file_name)。请改用os.path.realpath(file_name)
import os
profession_folder_path = '../fp/Updated/Profession/'
profession_files = os.listdir(profession_folder_path)
profession_texts = [open(os.path.realpath(file_name)).read() for file_name in profession_files]
print(profession_texts[0])对于权限,如果使用的是unix,则需要拥有对文件的读取权限和对目录的执行权限。运行下面的命令:
chmod -R a+rx '../fp/Updated/Profession/'https://stackoverflow.com/questions/43433555
复制相似问题