简体   繁体   中英

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. Ideally, I want a variable 'profession_texts' where each txt file is an element in a list. 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? 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). Use os.path.realpath(file_name) instead

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. Run below command:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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