0
f = open('buddy.txt','r')
data = f.read()
print(data)
f.close()

error:

 File "c:\Users\97798\Desktop\python\Chapter_09\01_files.py", line 10, in <module>
    f = open('buddy.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'buddy.txt'
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • The error message pretty much says it: you can't open for reading a file that doesn't already exist. If you open a file for writing/appending, then yes, it will create the file, but it doesn't make sense to do the same for reading. – Schol-R-LEA Jul 08 '22 at 03:32
  • Your python code and `buddy.txt` should be in the same directory. Make sure if both files are in the same directory, if not, move one of the file to other's. – Ellisein Jul 08 '22 at 03:35

1 Answers1

0

There are various modes to open files. See this to understand them. In your case, if you want to create a file when it doesn't exist and then continue, you can use w+. Also, in most cases you would want to handle errors that arise out of file operations with try and except statements.

fName = 'buddy.txt'
try:
    with open(fName, 'w+') as f:
        # do things with the file    
except OSError:
    print "Could not create/open file:", fName
viggnah
  • 1,709
  • 1
  • 3
  • 12