简体   繁体   中英

Finding absolute file path

I've been working on this Python project and just realized there's an issue. At first I thought it was just in Linux because I tried to create a command to open the file in the file path and then realized when it's ran anytime outside of the destination folder that it runs an error even in Windows. So it has to be an issue with my code in general. Basically I'm trying to call the program to read and print data from a text file.

help_text = open("files/help_text.txt","r") 
help_text_content = help_text.read()
print(help_text_content)

All I want to do is make sure that it reads the file no matter where the .py file is located. I can't do C:\\Location because if the user installs the file it might be located somewhere else. So I need an absolute location reader that knows where the file itself is.

The best way to handle file paths in Python is by using pathlib . This makes sure to handle all the details of using the right separators for paths and so on. I would use code like this:

import pathlib

# path of the current script:
parent = pathlib.Path(__file__).parent

help_file = parent / 'files' / 'help_text.txt'

# note: you can check that this file exists
if not help_file.is_file():
    raise FileNotFoundError('Help file not found')

with help_file.open() as f:
    help_text_content = f.read()

print(help_text_content)

I am thinking that probably using the os module could help you get the current working directory file, and then you could just append the help_text.txt to get the location:

import os
current_dir = os.getcwd()
# /C:/User/
path= os.path.join(current_dir, "help_text.txt")
# /C:/User/help_text.txt

Based on the information provided in the comments (txt file is always located in files/ which is always paired with the .py file) - you need to get the location of the py file. Note, it may be (and in case of this error obviously it is) different from the current working directory from which you execute the py script. For extended discussion see How do I get the path and name of the file that is currently executing?

Then you need to concatenate the path of the py file and "files/help_text.txt" . Of course you can use both os module or (better) pathlib module from standard library.

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