0
file = open('python-ai-info.txt', 'r')
words = file.read()
file.close()

Is this correct? Please help me fix it. I want to open file named python-ai-info.txt. I am currently getting error:

Traceback (most recent call last):
  File "C:\Users\sgcoder1337\AppData\Local\Programs\Python\Python38-32\rhyme ai.py", line 1, in <module>
    file = open('python-ai-info.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'python-ai-info.txt'
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Does this answer your question? [How to Open a file through python](https://stackoverflow.com/questions/19508703/how-to-open-a-file-through-python) – MLavrentyev Feb 18 '21 at 15:07
  • 2
    Python cannot find the file. Make sure the file is in the same folder as this script. –  Feb 19 '21 at 12:18

1 Answers1

1

Your code is correct, the error occurs because your directory is an invalid/nonexistent directory, try to use the complete directory like:

'C:/Users/Username/Desktop/Folder/filename.txt'

For opening file:

file = open(directory, flag)

Main flags (modes) are:

  1. "r" for reading text, throws an exception if the file doesn't exist
  2. "rb" for reading bytes, throws an exception if the file doesn't exist
  3. "w" for writing text, doesn't throw an exception if the file doesn't exist, but creates it
  4. "wb" for writing bytes, doesn't throw an exception if the file doesn't exist, but creates it
  5. "a" for appending text, throws an exception if the file doesn't exist
  6. "ab" for appending bytes, throws an exception if the file doesn't exist
  7. "x" for creating files without opening, throws an exception if the file already exist

For reading files:

txt = file.read() # get the whole text
line = file.readline() # get a line
lines = file.readlines() # get a list of lines

For writing text:

file.write('txt')

For closing:

file.close()

For more detailed and complete info have a look here

Leonardo Scotti
  • 1,069
  • 8
  • 21
  • Other than providing some of the relevant documentation, this answer appears to be wrong, in that the problem isn't that the "directory is an invalid/nonexistent directory", but that the file simple doesn't exist in the script's working directory. – Grismar Oct 08 '21 at 03:31