【问题标题】:setting working directory in python shell to import a text file在 python shell 中设置工作目录以导入文本文件
【发布时间】:2017-06-10 16:59:32
【问题描述】:

我想将一个文本文件从我的桌面导入到 python,但我得到一个错误。 谁能帮忙解释一下如何从桌面工作目录导入文本文件?

【问题讨论】:

  • 你能告诉我们你到目前为止尝试过的代码吗?你的文本文件里有什么?

标签: python directory set


【解决方案1】:
with open(r"/<path-to-desktop-from-root-directory>/desktop/samp.txt", 'r') as f:  # using raw string to path
    print(f.read())

with open("/<path-to-desktop>/samp.txt", 'r') as f:
    print(f.read())

您也可以直接在windows中使用路径,通过使用原始字符串i.e. r"C:\Users\&lt;username&gt;\Desktop\file.txt"或使用两个反斜杠i.e. "C:\\Users\\&lt;username&gt;\\Desktop\\file.txt"\(因为反斜杠被视为转义字符)

【讨论】:

    【解决方案2】:

    您的 python 程序和文本文件需要在同一个目录中。有几种方法可以在 python 中打开文件。如果你只是想阅读它,你可以这样做:

    file = open("File_Name.txt" , "r")
    print(file.read())
    

    如果要更改工作目录,请键入:

    import os
    os.chdir(path)
    

    【讨论】:

    • 问题是我不知道如何更改工作目录。你能帮帮我吗?
    • 您可以创建一个新文件,编写代码,然后将该 python 文件保存在与文本文件相同的目录中。
    • 我将使用显示如何更改工作目录的代码来编辑我的答案
    • 与其为整个程序设置路径,不如获取路径。即使要读取多个文件os.path.join() 也可以用来获取文件
    【解决方案3】:

    您可以使用 os.chdir 切换到一个目录。但你不必这样做。获取桌面路径的最佳方法是使用 expanduser 和 os.path.join 构建文件路径

    import os
    home = os.path.expanduser('~')
    file_path = os.path.join(home, 'Desktop', 'FileName.txt')
    with open(file_path, 'rb') as fo:
        data = fo.read()
    

    【讨论】:

      猜你喜欢
      • 2013-06-03
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      相关资源
      最近更新 更多