0

Try to open file that exists with visual Studio Code 1.43.2

This is the py file:

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)

This is the result:

PS C:\Users\Osori> & C:/Python/Python38-32/python.exe "c:/Users/Osori/Desktop/python_work/9_files and exceptions/file_reader.py"
Traceback (most recent call last):
  File "c:/Users/Osori/Desktop/python_work/9_files and exceptions/file_reader.py", line 1, in <module>        
    with open('pi_digits.txt') as file_object:
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'

enter image description here

The files exists and the spelling is correct. if the file_reader.py is run with IDLE runs just fine.

enter image description here

N. Wouda
  • 4,700
  • 1
  • 24
  • 32
  • `with open('c:/Users/Osori/Desktop/python_work/9_files and exceptions/pi_digits.txt') as file_object:`? – CristiFati Mar 28 '20 at 21:45
  • For simplicity, keep spaces out of filenames you use in coding. Not all systems (or coworkers) take kindly to it. – Noah Broyles Mar 28 '20 at 21:51
  • When OS says, the file is not there, the file is usually not there. Likely different CWD than you're expecting? Since the filename is relative to it. – Ondrej K. Mar 28 '20 at 22:44
  • _The files exists and the spelling is correct._ Then the program is checking the wrong location. – AMC Mar 28 '20 at 22:58

3 Answers3

0

You're outside of the working directory. In the terminal, you need to

cd '.\Desktop\python_work\9_files and exceptions\'

Then run the script.

Ernest Pokropek
  • 215
  • 1
  • 11
0

Visual Studio Code, allowed me to find the image by putting the absolute path instead the relative path

instead of this:

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)

This worked:

with open('/python_work/9_files and exceptions/pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)
N. Wouda
  • 4,700
  • 1
  • 24
  • 32
0

This worked on vscode [MacOS]

file_path = '/Users/osasumwenogbebor/Documents/dev/pythonCrashCourseVol2/chapter9/pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()


print(contents)
Osasu
  • 3
  • 5