繁体   English   中英

如何将txt文件的文件夹另存为python中的变量

[英]How to save a folder of txt files as a variable in python

我有一个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? 解决此错误后,我的代码是否可以实现我的目标?

您无需将文件名附加到目录为(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/'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM