0

I want to read all .csv files in a directory using Python. So when I googled it, I got this solution Find all files in a directory with extension .txt in Python

But when I entered

import glob
import os
os.chdir("/Desktop")

I am getting the following error

>>> os.chdir("~/Desktop")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '~/Desktop'

I am really confused where am I wrong? Thank you in advance.

2
  • In your code sample, you wrote os.chdir("/Desktop"), but in the error message it says os.chdir("~/Desktop"). Which one did you actually type? Commented Feb 19, 2014 at 13:18
  • sry its a typo :( ... i entered later Commented Feb 19, 2014 at 13:26

3 Answers 3

3

You need to expand ~ to actual home directory using os.path.expanduser

>>> import os
>>> os.path.expanduser('~/Desktop')
'/home/falsetru/Desktop'

Otherwise, ~ mean the directory ~ (literally ~).

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

Comments

0

os.chdir doesn't do tilde expansion. You need

os.chdir(os.path.join(os.getenv("HOME"), "Desktop"))

to go to ~/Desktop.

Comments

0
>>> import os   
>>> os.chdir('~/Desktop')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '~/Desktop'
>>> os.chdir(os.path.expanduser('~/Desktop'))
>>> os.getcwd()
'/users/xxx/Desktop'

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.