简体   繁体   English

如何使用Python 3获取文件的正确绝对路径?

[英]How to get the proper absolute path of a file using Python 3?

I am trying to get the absolute path of a file, but it's not working. 我正在尝试获取文件的绝对路径,但是它不起作用。 My Code is only showing the path to the directory of my running code . 我的代码仅显示我正在运行的代码目录的路径 This are the two way I have tried: 这是我尝试过的两种方法:

1) 1)

import os
print(os.path.abspath("More_Types.py"))

2) 2)

import os
print(os.path.realpath("More_Types.py"))

But I continue to get the full path to my running program. 但是,我继续获得运行程序的完整路径。 How can I get the correct path to file, that is located some where else in my Computer? 如何获得正确的文件路径,该路径位于计算机的其他位置?

PS: I am sorry I can't provide the output because it will reveal all the folders to my running program. PS:对不起,我无法提供输出,因为它将向我正在运行的程序显示所有文件夹。

More_Types.py , subdir/More_Types.py and ../More_Types.py are relative paths. More_Types.pysubdir/More_Types.py../More_Types.py是相对路径。

Outcome 结果

If you provide a relative path, realpath and abspath will return an absolute path relative to the current working directory. 如果提供相对路径, realpathabspath将返回相对于当前工作目录的绝对路径。 So essentially, they behave like os.path.join with the current working directory as first argument: 因此,从本质os.path.join ,它们的行为类似于os.path.join ,其中当前工作目录为第一个参数:

>>> import os.path
>>> os.path.join(os.getcwd(), 'More_Types.py') == os.path.abspath('More_Types.py')
True

This explains, why you get the result you explained. 这说明了为什么要得到说明的结果。

Explanation 说明

The purpose of abspath is to convert a relative path into an absolute path: abspath的目的是将相对路径转换为绝对路径:

>>> os.path.abspath('More_Types.py')
'/home/meisterluk/More_Types.py'

Unlike abspath , relpath also follows symbolic links. abspath不同,relpath也遵循符号链接。 Technically, this is dangerous and can get you caught up in infinite loops (if a link points to any of its parent directories): 从技术上讲,这很危险,并且可能使您陷入无限循环(如果链接指向其任何父目录):

>>> os.path.abspath('More_Types.py')
'/net/disk-user/m/meisterluk/More_Types.py'

Proposed solution 拟议的解决方案

However, if you want to retrieve the absolute path relative to some other directory, you can use os.path.join directly: 但是,如果要检索相对于其他目录的绝对路径,则可以直接使用os.path.join

>>> directory = '/home/foo'
>>> os.path.join(directory, 'More_Types.py')
'/home/foo/More_Types.py'
>>>

I think the best answer to your question is: You need to specify the directory the file is in. Then you can use os.path.join to create an absolute filepath. 我认为对您的问题的最佳答案是:您需要指定文件所在的目录。然后可以使用os.path.join创建绝对文件路径。

You could use this if you want: 您可以根据需要使用此功能:

import os
a='MoreTypes.py'

for root , dirs , files in os.walk('.') :

    for file in files:
        if file==a:
            print(os.path.join(root,file))

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

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