Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I load text files within a module in python?

Tags:

python

module

I have a python project that contains multiple modules and one module contains a .txt file of a long list of keywords.

How would I access the .txt file and load its content (the list of strings) into a variable in a .py script from another location (not the same directory)??

--- Library
         - Module_Alice
              - etc..
         - Module_Bob
              - assets
                   - audio
                   - video
                   - texts
                        - all_keywords.txt
              - unittests
                   - func 
                        - test_text_process.py

I need to load all keywords in all_keywords.txt into a variable in test_text_process.py

like image 531
Kid_Learning_C Avatar asked Oct 15 '25 14:10

Kid_Learning_C


1 Answers

Use open

You can use absolute path:

with open("/root/path/to/your/file.txt",'r') as fin:
    # Your reading logic

Or you can use relative path:

with open("../../your/file.txt",'r') as fin:
    # read it.

In the case you'll move the folder around and run it in other place, but not on the level of the python file, you might want to do relative import in this way:

import os.path as path
text_file_path = path.dirname(path.abspath(__file__)) + '/assets/texts/all_keywords.txt'

This way you can run your python file anywhere and still be able to use the text file. If you just do a relative you can't run your python from outside of its directory, i.e. like python path/to/script.py

like image 126
Rocky Li Avatar answered Oct 17 '25 04:10

Rocky Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!