user
user

Reputation: 914

Python open file, cannot find file

I am trying to open a csv file and load it, however it states that it cannot find the file, when it clearly exists in the file path i wrote it to be.

Code

#Load the CSV file into CSV reader
csvfile = open("C:/Users/Sam/Desktop/big data/workspace/test.csv",'rb')

Error

Traceback (most recent call last):
  File "C:/Users/Sam/Desktop/big data/workspace/yelpdatabase.py", line 16, in <module>
    csvfile = open("C:/Users/Sam/Desktop/big data/workspace/test.csv",'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Sam/Desktop/big data/workspace/test.csv'

Upvotes: 3

Views: 6693

Answers (3)

Ramon Zuniga
Ramon Zuniga

Reputation: 355

Try like this:

csvfile = open(r"C:/Users/Sam/Desktop/big data/workspace/test.csv","rb")

Make sure your file name is not test.csv.txt sometimes windows takes .csv as part of the filename

Tested using Python 2.7.12

Checkout http://shortcode.pro/code/open-csv-file-with-python/

Upvotes: 2

ShadowRanger
ShadowRanger

Reputation: 155323

Posting this since it's a likely cause of problems like this, if not necessarily in this specific case. Desktop (along with most other user folders) is a pseudo-magic folder, and you can't rely on it always being found at C:\Users\USERNAME\Desktop. In particular, just because you see a file on your desktop doesn't mean it's actually there. It could be in the All Users Desktop folder, and either of those could be redirected by the Windows Library folder redirection magic.

If you want to get the correct path to the user's desktop dynamically, you can use the pywin32 extension to do so:

from win32com.shell import shell, shellcon
shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, None, 0)

(hat tip to this answer), or to get the common Desktop folder for all users:

import win32com.client
objShell = win32com.client.Dispatch("WScript.Shell")
allUserDocs = objShell.SpecialFolders("AllUsersDesktop")

(hat tip to this answer).

Both approaches above might be replaceable on Vista and higher with code that calls SHGetKnownFolderPath (either with pywin32 if it supports it, or directly through a ctypes wrapper) using FOLDERID_Desktop and FOLDERID_PublicDesktop for the user specific and commonly shared Desktop folders.

Upvotes: 1

Illusionist
Illusionist

Reputation: 5489

Edited- try this

path = r"C:/Users/Sam/Desktop/big data/workspace/test.csv"
csvfile = open(path, 'rb')

Upvotes: -2

Related Questions