0

I am quite new to Python and I am having problems opening a file in Python. I want to open a text file called 'coolStuff' in a Folder on my Desktop and this is how I type in the command but I still get an error message. The file exists and so I do not understand why I get that error message.

open("coolStuff.txt","r")
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    open("coolStuff.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'coolStuff.txt'
Dokua
  • 1
  • 5

3 Answers3

2

If you want to simply supply a filename like coolStuff.txt without also providing a full directory, then you have to make sure that Python is running in the same directory as the file. If you aren't sure what directory Python is running in, try this:

import os
print(os.getcwd())
user3030010
  • 1,767
  • 14
  • 19
  • This is the directory python on my desktop is found in: C:\Program Files (x86)\Python35-32 – Dokua Nov 01 '16 at 21:37
1

You have two options: let's say your file is in C:\path\to\dir\coolStuff.txt

1.

open(r'C:\path\to\dir\coolStuff.txt','r')

2.

import os
os.chdir(r'c:\path\to\dir')
open('coolStuff.txt', 'r')
Jeff
  • 2,040
  • 3
  • 18
  • 19
  • Thanks for the help it worked! A little question though, what does the 'r' in the second line of code mean? – Dokua Nov 01 '16 at 21:56
  • The r converts the string to "raw text." Without the r, the slash character (\) has a special meaning. For example, '\n' gives a new line, and '\t' gives a tab. To avoid that, you would need two slashes, like "c:\\path\\to\\dir". I think it's easier to just add the r in the beginning, which tells python that \ isn't special. See this answer for more info: http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l – Jeff Nov 01 '16 at 22:03
0

Because the file you want to open is not in the current directory.You can find the file 'coolStuff.txt' in the terminal and launch your python environment at the same directory.