【问题标题】:Changing directory using OS module in Python在 Python 中使用 OS 模块更改目录
【发布时间】:2014-02-19 13:17:45
【问题描述】:

我想使用 Python 读取目录中的所有 .csv 文件。所以当我用谷歌搜索时,我得到了这个解决方案 Find all files in a directory with extension .txt in Python

但是当我进入时

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.chdir("/Desktop"),但在错误消息中却显示为os.chdir("~/Desktop")。您实际输入的是哪一个?
  • sry 这是一个错字:( ...我后来输入了

标签: python python-2.7 python-3.x


【解决方案1】:

您需要使用os.path.expanduser~ 扩展为实际的主目录

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

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

【讨论】:

    【解决方案2】:

    os.chdir 不进行波浪号扩展。你需要

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

    ~/Desktop

    【讨论】:

      【解决方案3】:
      >>> 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'
      

      【讨论】:

        猜你喜欢
        • 2018-08-06
        • 1970-01-01
        • 2011-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-25
        • 1970-01-01
        • 2014-01-27
        相关资源
        最近更新 更多