2

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

Kid_Learning_C
  • 2,605
  • 4
  • 39
  • 71

3 Answers3

3

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

Rocky Li
  • 5,641
  • 2
  • 17
  • 33
1

You can use something like this:

with open("../../assets/texts/all_keywords.txt") as f:
    keywords = f.readlines()

Now that keywords list variable contains all keywords on the file.

rockikz
  • 586
  • 1
  • 6
  • 17
1

This will read the file into a list of strings from that location.

with open('../assets/text/all_keywords.txt') as infile:
    list_of_strings = infile.readlines()
Stephen C
  • 1,966
  • 1
  • 16
  • 30
  • the relative path doesn't work: FileNotFoundError: [Errno 2] No such file or directory: '../assets/text/all_keywords.txt' – Kid_Learning_C Oct 18 '18 at 16:00
  • Depends on where you are running the file from. It may be `'Module_Bob/assets/text/all_keywords.txt'` or `'Library/Module_Bob/assets/text/all_keywords.txt'` – Stephen C Oct 18 '18 at 16:04