skip to Main Content

I wrote this code to open a file in python using VS CODE –

with open("Answer Words.txt") as Answer_Words_File:
    Answer_Words = Answer_Words_File.read()

But it says " FileNotFoundError: [Errno 2] No such file or directory: ‘Answer Words.txt’ "
This code worked when I earlier used PyCharm since the text file and my python project are in the same folder.

I also tried using the file path or writing –
Answer_Words = open("Answer Words.txt", "r")

Nothing worked

Do I need to use some library?

2

Answers


  1. I hope your terminal is not in right path if the file is not opening.
    To ensure that your file is available in the path you execute this code.
    You can use the code mentioned below

    import os
    current_directory = os.getcwd()
    files_in_directory = os.listdir(current_directory)
    
    # Print the list of files
    print("Files in the current directory:")
    for file in files_in_directory:
        print(file)
    
    Login or Signup to reply.
  2. My VS code default folder is in C:Useruser. If you save the ‘Answer Words.txt’ in the default folder, it should run properly. Or you can set the terminal to your operating folder, it works well too.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search