Reputation: 1
My program needs to read an external Notepad (.txt) file which has usernames and passwords. (Both the program and the document are on my desktop.) I used this code to read it.
file = open ("userDetails.txt", "r")
userDetails = file.readlines()
file.close()
But I keep getting this error:
FileNotFoundError: [Errno 2] No such file or directory: 'userDetails'
I tried putting them in a folder together, but still got the same error. Any ideas?
Upvotes: 0
Views: 10032
Reputation: 7260
I think your userDetails.txt does not reside in the python script working directory. So you have to specify your file names for input and output like e.g.:
# ----------------------------------------
# open file and select coordinates
# ----------------------------------------
pathnameIn = "D:/local/python/data"
filenameIn = "910-details.txt"
pathIn = pathnameIn + "/" + filenameIn
pathnameOut = "D:/local/python/data"
filenameOut = "910-details-reduced.txt"
pathOut = pathnameOut + "/" + filenameOut
fileIn = open(pathIn,'r')
fileOut = open(pathOut,'w')
Upvotes: 0
Reputation: 5386
Try and specify the full file path to the text file when you open it:
i.e /full/path/to/file.txt
such as /Users/Harrison/Desktop/file.txt
Right now it's likely that Python is looking for the file in the default Python working directory.
Also, it's a better practice when working with files to open it like this:
with open('/path/to/userDetails.txt') as file:
file_contents = file.readlines()
# or whatever else you'd like to do
... and here is an explanation as to why it's good to do it this way.
If you're having trouble locating the full file path, here's how you can do it for Mac and Windows.
Upvotes: 1