如何在windows for python上打开文件?有意料之外的问题

2024-06-28 20:02:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从python读取windows上的文本文件。我在mac终端上做过无数次,但我刚刚开始使用windows。首先要打开文件:

file = open("C:\users\lbryan05\documents\Training\python\Lynda\ch 2\words.txt",       'r')

,给出语法错误:

SyntaxError:(unicode错误)“UnicodeScape”编解码器无法解码位置2-3中的字节:截断\uxxx转义

我发现\u发生了一些奇怪的事情,所以我试着在路径前面加上一个r来加倍所有的反斜杠:

file = open(r"C:\users\lbryan05\documents\Training\python\Lynda\ch 2\words.txt",       'r')

因此,从这里我得到'没有这样的目录存在'。所以我认为windows是愚蠢的,并且隐藏了文件扩展名,所以我只需要发出文字.txt. 在这样做之后,我对以下错误感到惊讶:

PermissionError:[Errno 13]权限被拒绝:“path”。你知道吗

,这对我来说毫无意义,因为我当然可以访问它,所以我没有权限访问该文件。 我正在通过windows powershell(和sublime)执行python。你知道吗


Tags: 文件txt权限windows错误trainingopench
1条回答
网友
1楼 · 发布于 2024-06-28 20:02:19

如果文件不是太大,我建议将文件存储在该变量上,然后在python上执行所需的更改,然后使用“w”参数将整个文件与编辑的数据一起保存到文件中。你知道吗

试试这个:

# Open file to read it, and store it in a var.
with open("C:\\users\\lbryan05\\documents\\Training\\python\\Lynda\\ch 2\\words.txt", 'r') as f:
    file_content = f.read()
# Do something with that var, manipulate it like you want
file_content = file_content + "test"
# Open file to write on it, and write your manipulated var.
with open("C:\\users\\lbryan05\\documents\\Training\\python\\Lynda\\ch 2\\words.txt", 'w') as w:
    w.write(file_content)

相关问题 更多 >