简体   繁体   English

如何在Python中计算相对路径?

[英]How to calculate relative path in Python?

If I write 如果我写

current_path = os.path.dirname(os.path.abspath(__file__))

Then I get the path to the current file running. 然后,我得到当前正在运行的文件的路径。

What I need is the absolute path from the current file to: 我需要的是从当前文件到的绝对路径:

'../Data/my_data.csv'

How do I use os to output the absolute path to '../Data/my_data.csv' without changing my working directory or anything else? 如何在不更改工作目录或其他任何内容'../Data/my_data.csv'情况下,使用os将绝对路径输出到'../Data/my_data.csv'

You can use os.path.join: 您可以使用os.path.join:

current_path = os.path.dirname(os.path.abspath(__file__))
new_path = os.path.join(current_path, '..', 'Data', 'my_data.csv')

你可以做类似的事情

'{}/../Data/my_data.csv'.format(current_path)

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

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