With statement

https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

 

With Statement


You can also work with file objects using the with statement. It is designed to provide much cleaner syntax and exceptions handling when you are working with code. That explains why it’s good practice to use the with statement where applicable. 

One bonus of using this method is that any files opened will be closed automatically after you are done. This leaves less to worry about during cleanup. 

To use the with statement to open a file:

 

with open(“filename”) as file: 

 

Now that you understand how to call this statement, let’s take a look at a few examples.

 

with open(“testfile.txt”) as file:  
data = file.read() 
do something with data 

 

You can also call upon other methods while using this statement. For instance, you can do something like loop over a file object:

 

with open(“testfile.txt”) as f: 
for line in f: 
print line, 

 

You’ll also notice that in the above example we didn’t use the “file.close()” method because the with statement will automatically call that for us upon execution. It really makes things a lot easier, doesn’t it?

 

Using the With Statement in the Real World


To better understand the with statement, let’s take a look at some real world examples just like we did with the file handling functions.

 

To write to a file using the with statement:

 

with open(“hello.txt”, “w”) as f: 
f.write(“Hello World”) 

 

To read a file line by line, output into a list:

 

with open(“hello.txt”) as f: 
data = f.readlines() 

 

This will take all of the text or content from the “hello.txt” file and store it into a string called “data”.


Splitting Lines in a Text File


As a final example, let’s explore a unique function that allows you to split the lines taken from a text file. What this is designed to do, is split the string contained in variable data whenever the interpreter encounters a space character.

But just because we are going to use it to split lines after a space character, doesn’t mean that’s the only way. You can actually split your text using any character you wish - such as a colon, for instance.

The code to do this (also using a with statement) is:

 

with open(hello.text”, “r”) as f:
data = f.readlines()
 
for line in data:
words = line.split()
print words

 

If you wanted to use a colon instead of a space to split your text, you would simply change line.split() to line.split(“:”).

The output for this will be:

 

[“hello”, “world”, “how”, “are”, “you”, “today?”]
[“today”, “is”, “Saturday”]

 

The reason the words are presented in this manner is because they are stored – and returned – as an array. Be sure to remember this when working with the split function.

posted on 2018-11-27 14:34  cdekelon  阅读(79)  评论(0)    收藏  举报

导航