0

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?

Girrafish
  • 2,320
  • 1
  • 19
  • 32
Jacktavist
  • 1
  • 1
  • 2
  • Does the error report the filename as `userDetails`, as you say, or `userDetails.txt`, as your code indicates? Check that notepad has not added another `.txt` to the end of the filename, which it has a habit of doing. I suggest you use a more powerful and robust editor for text files, like Notepad++ for example. – cdarke Aug 26 '16 at 17:08
  • 1
    Welcome to Stack Overflow! Please go through the [tour](http://stackoverflow.com/tour), the [help center](http://stackoverflow.com/help) and the [how to ask a good question](http://stackoverflow.com/help/how-to-ask) sections to see how this site works and to help you improve your current and future questions, which can help you get better answers. Please have a look at [Python Language](http://stackoverflow.com/documentation/python/topics) too. – help-info.de Aug 26 '16 at 17:25
  • http://stackoverflow.com/questions/13000455/error-in-python-ioerror-errno-2-no-such-file-or-directory-data-csv possible duplicate hope this helps. – newlearner Aug 26 '16 at 18:27

2 Answers2

1

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.

Harrison
  • 5,095
  • 7
  • 40
  • 60
0

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')
help-info.de
  • 6,695
  • 16
  • 39
  • 41