python - Opening file in Python 3.4.2 shell
问题描述
I am using Python 3.4.2 on Windows 10 and am just getting into opening and read/writing to files from the Python shell
I did this test and got the following error message in spite of the fact that I had created the file beforehand (but not from the shell as that would not work either).
Can someone tell me what I haven't taken into consideration here because all my searches tell me this should work.
>>> import os
>>> helloFile = open('C:\\Users\\jennifer\\Hello.txt')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
helloFile = open('C:\\Users\\jennifer\\Hello.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\jennifer\\Hello.txt'
I did as John Gordon suggested and removed .txt from the pathname and it still didn't work.
Here is the directory and path for the file:
C:\Users\jennifer\Desktop\Hello
Finally, it has opened and will be very aware of the need to call the complete path in the future! Thank you
解决方案
您只需要在 Drive 后加上一个“\”,这是为了避免 unicode 错误。下面的代码假设您已经在 Powershell(Window 的 CMD)中运行了 Python。
此外,如果您想读取文件(即打印 CMD 中的内容),您需要通过将 r 放在文件路径之前使其可读。
file =open(r,'C:\\Users\jennifer\Desktop\Hello.txt')
要打印内容:
for i in file:
print(i)
然后按两次 Enter 以获取输出。
推荐阅读
- ios - 如何简化这个长 UIbutton 代码?
- powershell - 在从网络驱动器安装的应用程序上禁用 UAC
- css - 如何在 ReactJS 中进行转换
- typescript - 如何展平这个嵌套的 observable?
- python-3.x - 使用 Visual Studio Code 远程调试 python 代码时出错
- javascript - 了解 HTMLElement.hidden
- openssl - OpenSSL:第一个 num 太大 - 这是什么意思以及如何修复它?
- reactjs - 使用 React Router 将 redux 状态和 props 传递给另一个组件
- python - 当 bot 加入服务器时发送消息 [Discord.py]
- join - SSRS 一对多连接/查找数据集