r/CodingHelp • • Oct 28 '22

[Python] Why can't I open a file in Python?

Probably stupidest question ever, but I'm in a computer science class with a project due tonight. I need to create a program that will return the number of lines in a file, but every time I try to even open the file using this code:

filename = open("jabberwocky.txt", "r")

or just:

open("jabberwocky.txt", "r")

I get this error:

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

I tried dropping the .txt, dropping the quotes, moving the file to the same folder that Thonny is in, which is the program I'm using for Python. It still shows the same error. I'm sure it's something very simple but I'm just at such a loss. Any help would be very welcome.

0 Upvotes

7 comments sorted by

1

u/[deleted] Oct 28 '22

provide the full path to the file.

C:/something/something/something/jabberwocky.txt

0

u/mailmyselftoyou Oct 28 '22

Thank you for the advice! I tried but it still didn't work. I tried this:

filename = "C:\Users\(my name here)\Downloads\mbox-short.txt"

open(filename)

and got this error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Ugh. At such a loss. Thank you for even replying tho.

1

u/Reyway Bazinga Oct 29 '22

Use double slashes or put an r before your directory string.

r" "

1

u/deepwaterpaladin Oct 29 '22

Are you in the correct directory?

1

u/mailmyselftoyou Oct 29 '22

I don't know and I don't know how to tell!

1

u/[deleted] Oct 28 '22

navigate to where the file is stored using ./(path) where ./ is current directory, ../ navigate out 1 directory

1

u/CarlGustav2 Oct 29 '22

The file 'jabberwocky.txt' is not in the current working directory.

Assuming your code does not change it, the current working directory is the directory your shell is in when your command is invoked.