首页 > 解决方案 > Using relative paths in Python with AWS Cloud9

问题描述

Using AWS Cloud9 for a Python 3.x application. I am trying to open a file (using with open) in the same directory as the python file, however, it only works if I define the absolute path.


Relative Path

import csv

with open("test.csv", newline='') as f:
    reader = csv.reader(f, delimiter=' ', quotechar='|')
    for row in reader:
        print(', '.join(row))

Error in Terminal

Traceback (most recent call last):
 File "/home/ec2-user/environment/test/test.py", line 3, in <module>
   with open("test.csv", newline='') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'test.csv'

Absolute Path

import csv

with open("/home/ec2-user/environment/test/test.csv", newline='') as f:
    reader = csv.reader(f, delimiter=' ', quotechar='|')
    for row in reader:
        print(', '.join(row))

No Errors

标签: pythonamazon-web-servicescsvrelative-pathaws-cloud9

解决方案


发现了一个类似的问题,在下面发布了一个有效的答案。在python项目中使用相对路径读取文件

import csv
from pathlib import Path

path = Path(__file__).parent / "test.csv"

with path.open() as f:
    reader = list(csv.reader(f, delimiter=' ', quotechar='|'))
    for row in reader:
        print(', '.join(row))

推荐阅读