简体   繁体   English

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

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

I have a folder of txt folders that I want to import into python as a variable. 我有一个txt文件夹,我想将它作为变量导入python。 Ideally, I want a variable 'profession_texts' where each txt file is an element in a list. 理想情况下,我需要一个变量'profession_texts',其中每个txt文件都是列表中的一个元素。 This is what I have at the moment: 这是我目前所拥有的:

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])

Yet, when running this script, I get the error: 但是,在运行此脚本时,出现错误:

PermissionError: [Errno 13] Permission denied: '../fp/Updated/Profession/Athlete'

So I have two problems. 所以我有两个问题。 How do I get rid of this PermissionError? 如何摆脱此PermissionError? Once this error is resolved, will my code work for attaining my goal? 解决此错误后,我的代码是否可以实现我的目标?

You no need to append file name with directory as (profession_folder_path+file_name). 您无需将文件名附加到目录为(profession_folder_path + file_name)。 Use os.path.realpath(file_name) instead 使用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])

and for permissions you need to have read permissions on file and execute permission on directory if you are using unix. 对于权限,如果您使用的是UNIX,则需要具有文件读取权限和目录执行权限。 Run below command: 运行以下命令:

chmod -R a+rx  '../fp/Updated/Profession/'

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

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