Python:无法打开和读取文件

问题描述 投票:0回答:3

我对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()

但我得到的错误相同。

python
3个回答
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()

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


0
投票

我想你可能有这个问题,因为你没有包含完整的文件名。

你应该试试:

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

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

filename = open(newfile.txt

0
投票

我有同样的问题。这就是我如何做对的。

你的代码:

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

试试这个:

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

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.