Reading a file: No such file or directory

Viewed 1280

I want to read a txt file test_case_tranfromation.txt I just created in my directory but whenever I try to open it, I'm getting the error.

I tried:

f = open("/Users/stanislavjirak/Documents/KBC_GROUP/rasa-cz/rasa_cz/rasa_extension/test/test_case_transformation.txt", "r")
print(f.readline())

with open("test_case_transformation.txt") as f:
    print(f.read())

Both yielded:

FileNotFoundError: [Errno 2] No such file or directory: 'test_case_transformation.txt'

I can physically see the file there and even copied$pasted the name.

What am I doing wrong?

5 Answers

There are two ways to get files in Python. Either you use the full absolute path of the file, e.g.: "C:/Users/[username]/...", or you give a path relative to the .py file you're running. For example, let's say your .py file is located in "C:/Users/[username]/file.py", then you could access a txt file that is in the same directory, e.g.: "c:/Users/[username]/file.txt" like this:

with open("file.txt") as f:
    ...

If your file is located at the root directory, you need to append the file name to the current working directory.

import os
with open(os.getcwd() +"\\test_case_transformation.txt") as f:

This:

with open("test_case_transformation.txt") as f:
    print(f.read())

can be used if the .py file and the .txt file are in the same directory. Otherwise you should write the whole path to the file you want to open:

with open("/path/to/file/test_case_transformation.txt") as f:
    print(f.read()) 

If you use Windows I suggest you do it like this:

with open(r"C:\path\to\file\test_case_transformation.txt") as f:
    print(f.read())

When ever you get file not found error, it is definite means file is not present at the location. If you are creating any file and trying to read it after wards, try to use the relative paths for writing and reading. E.g.

    from pathlib import Path

    parents = Path(__file__).resolve().parents. // get all the parents of 
    current file location
    root_path = str(parents[0])

    //Create file
    with Path(root_path, "file_name.txt").open(mode="w") as fp:
       fp.write("some data")

    //read file
    with Path(root_path, "file_name.txt").open(mode="r") as fp:
      for line in fp:
         ---do something-----

this way you will not loose the context of file creation and reading.

open("test_case_transformation.txt") is a relative to the current working directory. Either make sure to change the working directory or use a full path.
Example directory:

/tmp
├── test_case_transformation.py
└── test_case_transformation.txt

test_case_transformation.py:

import os
print(os.path.exists('test_case_transformation.txt'))

Calling from bash:

cd /tmp; python test_case_transformation.py                                                                       
True

cd /; python /tmp/test_case_transformation.py                                                                            
False
Related