3

I went through couple answers on forum already but without any success. I am using Linux mint, Python 3.6.0 and i am trying to open CSV in Python but then error occurs:

  file = open("~/Desktop/xyz/city.csv", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/xyz/city.csv'

My code:

import csv

file = open("~/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)

I also tried to move the file to desktop as in some answers i found, instead of path i used "city.csv". Still doesn't work.

Completely new to Linux and just can't find why this isn't working.

Each reply appreciated!

3
  • How are you running the command? Just form the terminal or from something like cron? Possibly "~" is not expanding the way you think it should. Commented Feb 10, 2017 at 17:14
  • I am using Pycharm for running all code. Commented Feb 10, 2017 at 17:15
  • As you can see by the other answers, everyone thinks its the ~. Try something like: import os print os.path.abspath("~") and see if thats what you expect Commented Feb 10, 2017 at 17:25

3 Answers 3

3

You should'nt use '~' to specify the path of your directory but the full path instead. E.g. :

import csv

file = open("/home/user/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)

If you need to use the tilde, you should then use os.path.expanduser('~/Desktop/xyz/city.csv'). E. g. :

import csv

file = open(os.path.expanduser("~/Desktop/xyz/city.csv"), "rb")
reader =csv.reader(file)

The reason for that is that the "tilde expansion" is a user interface feature that is not recognized by the file system: http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion

Sign up to request clarification or add additional context in comments.

1 Comment

I've seen your comment for the other answer but I'm not allowed to type there atm. If you want to know the full path to access a directory under linux, use the command pwd which will print the full path to the current directory :)
0

Try using the full file path, something like this:

file = open("/home/[username]/Desktop/xyz/city.csv", "rb")

1 Comment

It did the work, crap, i also tried /home/desktop but didn't thought of adding username there. Thanks mate!
0

Usually ~ does not expand properly. I have found that when it is needed, put $HOME environment variable value into a python variable and then use join to attach it as a prefix to the file name relative position. This also allows you to move the file to a different location and create a function that will allow you to redefine the prefix.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.