0

the following Python code is to prompt user to specify a file name (which is stored in the variable 'file_name') and then read data from the file.

file_name = input("Enter the file name: ")

# Open the file and read the data
with open(file_name, "r") as file:
    lines = file.readlines()

When i run this and provide a file name, it gives a FileNotFoundError. The file I am using is in the same folder as the .py file so why is it not recognising the file? am i missing something?

I have tried moving the file to several locations such as the C: root directory but it still does not recognise it

  • We need to know: the exact location of the file, the exact stacktrace, the exact value of the variable "file_name". – Itération 122442 Apr 29 '23 at 16:56
  • *"The file I am using is in the same folder as the .py file so why is it not recognising the file?"* Python doesn't look in the same folder as the script file, it looks in the working directory of the process, which you can check using `os.getcwd()`. See: https://stackoverflow.com/questions/5137497/find-the-current-directory-and-files-directory – slothrop Apr 29 '23 at 16:57
  • @slothrop how do i check the cwd in vs code? – Mohammed Yakub Apr 29 '23 at 17:03
  • `print(os.getcwd())` in your script, so you can see exactly what directory VSCode is running it from. – slothrop Apr 29 '23 at 17:06
  • @slothrop insert that into my code? I did that and it gave a NameError saying 'os' is not defined. I dont have a script separate from that – Mohammed Yakub Apr 29 '23 at 17:15
  • Add a line `import os` at the start of your script to use functions from the `os` module – slothrop Apr 29 '23 at 17:16
  • @slothrop it worked, but my cwd is the directory where my file is located and it still doesnt recognise it – Mohammed Yakub Apr 29 '23 at 17:20
  • OK that's weird - what's your cwd, what's the filename and what's the exact error? – slothrop Apr 29 '23 at 17:23
  • @slothrop cwd: C:\Users\hello\Documents\Computer Science\data analysis practice filename: prec_data Error: FileNotFoundError: [Errno 2] No such file or directory: 'prec_data' – Mohammed Yakub Apr 29 '23 at 17:41
  • Thanks, and the filename is literally only `prec_data` ? With no file extension? – slothrop Apr 29 '23 at 17:42
  • @slothrop sorry it was .pre. I was doing .txt, which it was originally so that was the mistake. it is fixed now, but there is another error, will try and work through it right now – Mohammed Yakub Apr 29 '23 at 17:45
  • OK, one problem solved at least, good luck! – slothrop Apr 29 '23 at 17:47

0 Answers0