使用 Python 中的操作系统模块更改目录



我想使用 Python 读取目录中的所有.csv文件。所以当我用谷歌搜索它时,我得到了这个解决方案在 Python 中查找扩展名为 .txt 的目录中的所有文件

但是当我进入时

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

我收到以下错误

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

真的很困惑我错在哪里?提前谢谢你。

您需要

使用 os.path.expanduser~扩展到实际的主目录

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

否则,~表示目录~(字面意思是~)。

os.chdir

做波浪号扩展。你需要

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

~/Desktop.

>>> 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'

最新更新