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.

Community
  • 1
  • 1
Satadip Saha
  • 137
  • 1
  • 3
  • 11

3 Answers3

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 ~).

falsetru
  • 357,413
  • 63
  • 732
  • 636
0

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

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

to go to ~/Desktop.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
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'
Magnus Lyckå
  • 336
  • 2
  • 8