首页 > 解决方案 > 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

标签: python

解决方案


您只需要在 Drive 后加上一个“\”,这是为了避免 unicode 错误。下面的代码假设您已经在 Powershell(Window 的 CMD)中运行了 Python。

此外,如果您想读取文件(即打印 CMD 中的内容),您需要通过将 r 放在文件路径之前使其可读。

file =open(r,'C:\\Users\jennifer\Desktop\Hello.txt')

要打印内容:

for i in file:
    print(i)

然后按两次 Enter 以获取输出。


推荐阅读