0

Im attempting to open a file in a program but I got hit with this error: "[Errno 2] No such file or directory"

I saw that getting the absolute path instead of the relative path is a potential fix, but I'm not sure how to go about doing that. If anyone has a way that I can get the absolute path of my file or has another way this can be fixed please let me know. Thank you in advance!

filename = "customer_records.txt"
with open(filename) as f:
    lines = f.read().splitlines()

a = []

for line in lines:
    a.append(line.split(","))

2 Answers2

0

This will print the current working directory.

import os

print(os.getcwd())

If the file is not in this folder then passing just the filename will not work. You need to pass the full path (either relative or absolute).

For instance

open("/home/my_user_name/some_folder/customer_records.txt")
darcamo
  • 3,294
  • 1
  • 16
  • 27
0

There are many ways to get the path of the file. Here is one way of getting the full path of your customer_records.txt file, assuming it's in the same directory as the running Python file:

import os

print ( os.path.join(os.path.dirname(os.path.abspath(__file__)),'customer_records.txt') )
pink spikyhairman
  • 2,391
  • 1
  • 16
  • 13