繁体   English   中英

如何在Windows上为python打开文件? 遇到意外问题

[英]How do you open a file on windows for python? having unexpected issues

我想从python读取Windows上的文本文件。 我已经在Mac终端上完成了一百万次,但是刚开始使用Windows。 首先是打开文件:

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

,它给出语法错误:

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

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

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

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

PermissionError:[Errno 13]权限被拒绝:“路径”。

,这对我为什么没有权限,因为我当然可以访问它就毫无意义。 我正在通过Windows Powershell(和Sublime)执行python。

如果文件不是太大,建议将文件存储在该变量上,然后在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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM