python相对路径读取文件_在python项目中使用相对路径读取文件

1586010002-jmsa.png

Say I have a python project that is structured as follows:

project

/data

test.csv

/package

__init__.py

module.py

main.py

__init__.py:

from .module import test

module.py:

import csv

with open("..data/test.csv") as f:

test = [line for line in csv.reader(f)]

main.py:

import package

print(package.test)

When I run main.py I get the following error:

C:\Users\Patrick\Desktop\project>python main.py

Traceback (most recent call last):

File "main.py", line 1, in

import package

File "C:\Users\Patrick\Desktop\project\package\__init__.py", line 1, in

from .module import test

File "C:\Users\Patrick\Desktop\project\package\module.py", line 3, in

with open("../data/test.csv") as f:

FileNotFoundError: [Errno 2] No such file or directory: '../data/test.csv'

However, if I run module.py from the package directory I get no errors. So it seems that the relative path used in open(...) is only relative to where the originating file is being run from (i.e __name__ == "__main__")? I don't want to use absolute paths. What are some ways to deal with this?

解决方案

Relative paths are relative to current working directory.

If you do not your want your path to be, it must be absolute.

But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:

import csv

import os.path

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

path = os.path.join(my_path, "../data/test.csv")

with open(path) as f:

test = list(csv.reader(f))

Note, from python 3.4, __file__ is always absolute for imported modules and you can drop the os.path.abspath part in this example. Not that it is strictly necessary, but it avoids surprises if you change the current working directory at some point and your module was imported using a relative path.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Python 相对路径是相对于当前工作目录的路径。可以使用 `os` 模块的 `getcwd()` 函数来获取当前工作目录。假设我们要读取当前工作目录下的一个名为 `example.txt` 的文件,可以使用以下代码: ```python import os # 获取当前工作目录 current_dir = os.getcwd() # 文件相对路径 relative_path = "example.txt" # 拼接绝对路径 absolute_path = os.path.join(current_dir, relative_path) # 打开文件读取内容 with open(absolute_path, "r") as f: content = f.read() print(content) ``` 在上述代码,首先使用 `os.getcwd()` 函数获取当前工作目录,然后将要读取文件相对路径存储在变量 `relative_path` 。接下来,使用 `os.path.join()` 函数将当前工作目录相对路径拼接成绝对路径存储在变量 `absolute_path` 。最后,使用 `with open()` 语句打开文件读取内容,最后将读取的内容打印出来。 ### 回答2: Python相对路径是相对于当前脚本文件的路径来定位其他文件的路径。相对路径可以使用不同的方法来实现。 方法一是使用`os`模块的`path`方法来获取当前脚本的绝对路径,然后使用相对路径来定位其他文件的路径。代码示例如下: ```python import os # 获取当前脚本的绝对路径 current_path = os.path.abspath(__file__) # 获取当前脚本所在的目录路径 dir_path = os.path.dirname(current_path) # 使用相对路径来定位其他文件的路径 file_path = os.path.join(dir_path, 'otherfile.txt') # 打开文件读取内容 with open(file_path, 'r') as file: content = file.read() print(content) ``` 方法二是使用`__file__`变量直接获取当前脚本的路径,然后使用相对路径来定位其他文件的路径。代码示例如下: ```python import os # 获取当前脚本的路径 current_path = os.path.dirname(os.path.realpath(__file__)) # 使用相对路径来定位其他文件的路径 file_path = os.path.join(current_path, 'otherfile.txt') # 打开文件读取内容 with open(file_path, 'r') as file: content = file.read() print(content) ``` 无论使用哪种方法,相对路径的基准点都是当前脚本文件的路径。因此,如果要读取其他文件,可以使用相对路径来定位文件的位置,并利用`open`函数来打开文件读取内容。 ### 回答3: 在Python相对路径是相对于当前工作目录而言的路径。如果要使用相对路径读取文件,可以采取以下步骤: 1. 确定当前工作目录使用`os`模块的`getcwd()`方法可以获取当前工作目录。 ```python import os current_dir = os.getcwd() ``` 2. 创建文件路径:根据当前工作目录文件位置,创建文件路径。假设文件名为`example.txt`,并且位于当前工作目录下的`data`文件。 ```python file_path = os.path.join(current_dir, 'data/example.txt') ``` 3. 打开文件读取内容:使用`open()`函数打开文件,然后使用文件对象的`read()`方法读取文件内容。 ```python with open(file_path, 'r') as file: content = file.read() ``` 完整的代码如下所示: ```python import os current_dir = os.getcwd() file_path = os.path.join(current_dir, 'data/example.txt') with open(file_path, 'r') as file: content = file.read() ``` 在上述例子,假设`example.txt`文件位于当前工作目录下的`data`文件。根据实际情况,你可以修改文件名和文件路径来适应你的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值