【发布时间】:2017-06-10 16:59:32
【问题描述】:
我想将一个文本文件从我的桌面导入到 python,但我得到一个错误。 谁能帮忙解释一下如何从桌面工作目录导入文本文件?
【问题讨论】:
-
你能告诉我们你到目前为止尝试过的代码吗?你的文本文件里有什么?
我想将一个文本文件从我的桌面导入到 python,但我得到一个错误。 谁能帮忙解释一下如何从桌面工作目录导入文本文件?
【问题讨论】:
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\<username>\Desktop\file.txt"或使用两个反斜杠i.e. "C:\\Users\\<username>\\Desktop\\file.txt"\(因为反斜杠被视为转义字符)
【讨论】:
您的 python 程序和文本文件需要在同一个目录中。有几种方法可以在 python 中打开文件。如果你只是想阅读它,你可以这样做:
file = open("File_Name.txt" , "r")
print(file.read())
如果要更改工作目录,请键入:
import os
os.chdir(path)
【讨论】:
os.path.join() 也可以用来获取文件
您可以使用 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()
【讨论】: