Python opens and reads files with one liner

I know that the best way to open a file for reading / writing is using with

instead

 f = open('file.txt', 'w') f.write('something') f.close() 

we must write -

 with open('file.txt', 'w') as f: f.write('something') 

but what if i just want to read the file? I can do it

 with open('file.txt') as f: print (f.read()) 

but what is the problem in the bottom line

print (open('file.txt').read())

OR

 alist = open('file.txt').readlines() print (alist) 

Does it automatically close the file after executing this statement? Is this the standard way to write? should we write like that?

other than that - should I open the file in a function and pass a pointer to another for writing, or should I declare it a global variable? i.e

 def writeto(f): #do some stuff f.write('write stuff') def main(): f = open('file.txt', 'w') while somecondition: writeto(f) f. close() 

OR

 f = open('file.txt', 'w') def writeto(): #do some stuff f.write('write stuff') def main(): while somecondition: writeto() f. close() 
+5
source share
2 answers

Solving your questions in order,

"What happened to print(open(file).readlines()) ?"

Well, you delete the file object after using it so that you cannot close it. Yes, Python automatically closes your file, but on its terms, and not on yours. If you are just playing in a shell or terminal, this is probably good because your session is likely to be short and there will usually not be resource competition over files. However, in a production environment, leaving files open for the life of your script can be disruptive to performance.

As for creating a function that takes a file object and writes to it, then, in essence, what file.write . Note that the file descriptor is an object with methods, and these methods behind the scenes take self (that is, an object) as the first argument. So the record itself is already a function that takes a file descriptor and writes to it! You can create other functions if you want, but you essentially duplicate the default behavior without any tangible benefits.

Keep in mind that your first function looks something like this:

 def write_to(file_handle, text): return file_handle.write_to(text) 

But what if I called file_handle self instead?

 def write_to(self, text): return self.write(text) 

Now it looks like a method instead of a standalone function. In fact, if you do this:

 f = open(some_file, 'w') # or 'a' -- some write mode write_to = f.write 

you have almost the same function (only attached to this file_handle)!

As an exercise, you can also create your own context managers in Python (for use with the with operator). You do this by defining __enter__ and __exit__ . So technically you can also override this:

 class FileContextManager(): def __init__(self, filename): self.filename = filename self._file = None def __enter__(self): self._file = open(self.filename, 'w') def __exit__(self, type, value, traceback): self._file.close() 

and then use it like:

 with FileContextManager('hello.txt') as filename: filename.write('Hi!') 

and he will do the same.

The thing is that Python is flexible enough to do all this if you need to override this and add to the default behavior, but in the standard case there is no real benefit to this.


As for the program in your example, there is nothing wrong with practically any of these methods in the trivial case. However, you are not able to use the with statement in your main function:

 def main(): with open('file.txt') as filename: while some_condition: filename.write('some text') # file closed here after we fall off the loop then the with context if __name__ == '__main__': main() 

If you want to create a function that takes a file descriptor as an argument:

 def write_stuff(file_handle, text): return file_handle.write(text) def main(): with open('file.txt', 'w') as filename: while some_condition: write_stuff(filename, 'some text') # file closed here after we fall off the loop then the with context if __name__ == '__main__': main() 

Again, you can do this in different ways, so what is best for what you are trying to do? What is the most readable?

"Should I open the file in a function and pass a pointer to another for writing, or should I declare it as a module variable?"

Well, as you saw, either will work. This question is highly context sensitive and, as a rule, best practice dictates that a file is opened for the least amount of time and in the smallest reasonable amount. So what do you need to access your file? If there are a lot of things in the module, perhaps a variable or module level class for storing it is a good idea. Again, in the trivial case, just use with as above.

+3
source

The problem is that you put a space between print and (). This code works well in Python3:

 print(open('yourfile.ext').read()) 
-3
source

Source: https://habr.com/ru/post/1214021/


All Articles