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

假设我有一个python项目,结构如下:

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)

当我运行main.py时,我收到以下错误:

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'

你可能感兴趣的:(python读文件相对路径)