1

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

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
Zack
  • 51
  • 6
  • your script is in here `/home/ec2-user/environment/Lab5/lab5.py` your file is in here `"/home/ec2-user/environment/test/test.csv"`, so if you want to use relative path in your code, you should call `open("../../test/test.csv", newline='')` – warungman Apr 21 '20 at 05:41
  • or simply put your file at the same folder as your script – warungman Apr 21 '20 at 05:42
  • Sorry, I changed it to a simpler path for the question. Updating question. – Zack Apr 21 '20 at 05:44

2 Answers2

1

Found a similar question, posted an answer below that works. Reading file using relative path in python project

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))
Zack
  • 51
  • 6
0

I can't comment so I am gonna answer here and hope it is right for you. AWS uses Linux OSes, if you want to use a file in Linux in the same folder the script you are running, you have to prepend ./ in the file's name, e.g. in your case:

import csv

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