python - 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
解决方案
发现了一个类似的问题,在下面发布了一个有效的答案。在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))
推荐阅读
- android - RecyclerView android中的Admob原生广告
- mongodb - MongoDb SpringBoot 更新 currentUser
- python - 如何使用 Python 证明一个根式表达式是三次多项式的根
- azure - 在不维护上次报告的版本的情况下,是否有办法仅在设备孪生报告的属性发生更改时获取事件?
- python - 微小的 pyspark 数据框爆炸成一个巨大的数据框
- java - 如何使用 IN 子句执行 PreparedStatement?
- c++ - C++ 代码中的性能下降(恶化)
- c++ - C++ 数据库使用 SQL ODBC 从表中获取行数组
- javascript - 在下拉菜单中的元素周围添加 div 包装器
- ios - 带有常规文本的 SwiftUI 低不透明度按钮