简体   繁体   English

查找绝对文件路径

[英]Finding absolute file path

I've been working on this Python project and just realized there's an issue.我一直在研究这个 Python 项目,刚刚意识到存在一个问题。 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.起初我以为它只是在 Linux 中,因为我试图创建一个命令来打开文件路径中的文件,然后意识到当它在目标文件夹之外的任何时间运行时,即使在 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.我想要做的就是确保无论.py文件位于何处,它都能读取文件。 I can't do C:\\Location because if the user installs the file it might be located somewhere else.我不能做C:\\Location因为如果用户安装文件它可能位于其他地方。 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 .在 Python 中处理文件路径的最佳方法是使用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:我想可能使用os模块可以帮助您获取当前工作目录文件,然后您可以附加help_text.txt以获取位置:

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.根据注释中提供的信息(txt 文件始终位于 files/ 中,它始终与 .py 文件配对)-您需要获取 py 文件的位置。 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.请注意,它可能(并且在出现此错误的情况下显然是)与您执行 py 脚本的当前工作目录不同。 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" .然后你需要将 py 文件的路径和"files/help_text.txt" Of course you can use both os module or (better) pathlib module from standard library.当然,您可以使用标准库中的os模块或(更好的) pathlib模块。

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

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