简体   繁体   English

Python:无法打开和读取文件

[英]Python: Unable to open and read a file

I am totally new to python.我对python完全陌生。 I was trying to read a file which I already created but getting the below error我试图读取我已经创建的文件但收到以下错误

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

My code:我的代码:

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

Also I tried我也试过

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

But same errors I am getting.但是我遇到了同样的错误。

Try:尝试:

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

First you validate that file, that it exists.首先验证该文件是否存在。 Then you open it.然后你打开它。 With wrapper is more usefull, it closes your file, after you finish reading.使用包装器更有用,它会在您阅读完后关闭您的文件。 So you will not stuck with many open descriptors.所以你不会被许多打开的描述符所困扰。

I think you're probably having this issue because you didn't include the full filename.我认为您可能遇到此问题,因为您没有包含完整的文件名。

You should try:你应该试试:

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

*Also if you're running this python file in the same location as the target file your are opening, you don't need to give the full directory, you can just call: *此外,如果您在与打开的目标文件相同的位置运行此 python 文件,则无需提供完整目录,只需调用:

filename = open(newfile.txt

I had the same problem.我有同样的问题。 Here's how I got it right.这就是我做对的方式。

your code:你的代码:

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

Try this:尝试这个:

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

Hope it helps.希望能帮助到你。

I am using VS code.我正在使用 VS 代码。 If I am not using dent it would not work for the print line.如果我不使用 dent,它将不适用于打印线。 So try to have the format right then you will see the magic.因此,请尝试使用正确的格式,然后您就会看到魔力。

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

or without format like this:或没有这样的格式:

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

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

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