Python:无法打开和读取文件

时间:2014-11-02 21:21:49

标签: python

我对python完全不熟悉。 我试图读取一个我已创建的文件,但收到以下错误

File "C:/Python25/Test scripts/Readfile.py", line 1, in <module>
    filename = open('C:\Python25\Test scripts\newfile','r')
IOError: [Errno 2] No such file or directory: 'C:\\Python25\\Test scripts\newfile

我的代码:

filename = open('C:\Python25\Test scripts\newfile','r')
print filename.read()

我也试过

filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()

但我得到的错误相同。

4 个答案:

答案 0 :(得分:1)

尝试:

fpath = r'C:\Python25\Test scripts\newfile'
if not os.path.exists(fpath):
  print 'File does not exist'
  return

with open(fpath, 'r') as src:
  src.read()

首先验证该文件是否存在。 然后你打开它。使用包装器更有用,它会在您完成阅读后关闭您的文件。所以你不会坚持使用许多开放描述符。

答案 1 :(得分:0)

我认为您可能遇到此问题,因为您没有包含完整的文件名。

你应该尝试:

filename = open('C:\Python25\Test scripts\newfile.txt','r')
print filename.read()

*此外,如果您在与正在打开的目标文件相同的位置运行此python文件,则无需提供完整目录,只需调用:

filename = open(newfile.txt

答案 2 :(得分:0)

我有同样的问题。这是我正确的方法。

您的代码:

filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()

尝试一下:

with open('C:\\Python25\\Test scripts\\newfile') as myfile:
print(myfile.read())

希望有帮助。

答案 3 :(得分:0)

我正在使用VS代码。如果我不使用凹痕,则它不适用于打印线。因此,尝试正确设置格式,然后您将看到魔术。

with open("mytest.txt") as myfile:
    print(myfile.read())

或没有这样的格式:

hellofile=open('mytest.txt', 'r')
print(hellofile.read())