-3

I am currently learning python and my instructor is telling me to open a text file using the open() meathod. I get the following error each time:

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

I have tried using online guides but all I could find was for .csv files, whereas I'm trying to open a text file. My complete code is as follows:

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

I've tried writing the file 'movies.txt' in VS code, and in my notepad, and then saving it to the same directory as the code but no use. I have also attempted to use a more exact file source, but still the same error. Sadly, google didn't have too much information for text files so I have to come here. Is there something I have to change in VS settings? I also tried my code in IDLE but not response either.

Thanks, Stan

Stan U.
  • 1
  • 7

4 Answers4

0

First of all you have to make sure that the file you are looking is in the same folder as your script as you are giving just the name and not the path. Then the code to read a file misses a parameter:

with open('movies.txt', 'r') as file_object:
    contents = file_object.read()
    print(contents.strip())

r: read
w: write
a: append

0

The code is ok, the problem is finding the object as the error states. As you write it, it looks like "movies.txt" is in the same directory as the script. Are you sure they are in the same directory? Otherwise you will have to set the whole route

0

This is not about the directory your code is in. This is about the current working directory. These two directories may or may not be the same in some specific circumstance, but treating them as the same thing will lead to confusion in the future.

I don't know about VS Code (haven't worked with it), but all IDEs I've worked with have an option to set the current working for code you're running from the IDE.

Sören
  • 1,803
  • 2
  • 16
  • 23
  • I found that insted of opening the file in VS code, I can just open the foled and then the code works perfectly. Im searching the settings for what you suggested. – Stan U. Nov 13 '22 at 11:43
0

I ended up using the run & debug function in VS, and it works. I dont understand what it debugged. All the information it gave me was my .vscode files? I guess its fine for now? Is it possible that the issue was caused by something else I have downloaded on my laptop?

Thanks, Stan

Stan U.
  • 1
  • 7
  • Please follow the advice in comments and other answers to properly troubleshoot what the problem was and what might've solved it. Don't post this as an answer just to say you don't really know what the answer is. – Zegarek Nov 17 '22 at 10:21