[Python practice 06] Save data to a file

Source: Internet
Author: User

Previously, we read data from the file, processed the data, and printed it using the print statement. However, we often need to save the processed data to a file. So here we will introduce how to save the processed data to a file, because we only processed the data in a very simple way before, here we will first perform some complex processing on the data.

Write a piece of code for program data processing to implement the following functions: create two empty charts named manand otherand read the content in the sketch.txt file (this file is included in [Python practice 04]), and use ":" To separate, save as role and line_spoken respectively, and save the corresponding content to the corresponding man and other lists through role as man or other.
The Code is as follows:
man= []other = []try:    data = open('sketch.txt')    for each_line in data:        try:            (role,line_spoken) = each_line.split(":",1)            line_spoken = line_spoken.strip()            if role == 'Man':                man.append(line_spoken)            elif role == 'Other Man':                other.append(line_spoken)        except ValueError:            pass    data.close()except IOError:    print('The datafile is missing!')print(man)print(other)
The running result is as follows:
>>> ================================ RESTART ================================>>> ['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!', 'Nonsense!', "No it isn't!"]>>> 
Next, we need to save the content in list man and other to a file. First, we need to open a file in write mode.
The code for opening a file in write mode is as follows:
out = open('sketch.txt','w')
In this case, we opened sketch.txt in a written form, and then we can write the content to this file using the following statement:
print('Hello World',file=out)
In this way, we will write the Hello world character string into the sketch.txt file. Finally, don't forget to close the stream:
out.close()
Then we can change the previous code to save the content of man_data.txtand other_data.txt respectively. The Code is as follows:
man= []other = []try:    data = open('sketch.txt')    for each_line in data:        try:            (role,line_spoken) = each_line.split(":",1)            line_spoken = line_spoken.strip()            if role == 'Man':                man.append(line_spoken)            elif role == 'Other Man':                other.append(line_spoken)        except ValueError:            pass    data.close()except IOError:    print('The datafile is missing!')print(man)print(other)try:    man_file = open('man_data.txt','w')    other_file = open('other_data.txt','w')    print(man,file=man_file)    print(other,file=other_file)    man_file.close()    other_file.close()except IOError:    print('File Error')
We can see that the file write operation is added at the end of the previous Code, and other code is not changed. Run the above Code to find the two files generated in the corresponding folder:

The contents of the two files are as follows: man_data.txt:
['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']
Other_data.txt:
["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!', 'Nonsense!', "No it isn't!"]
However, our code is relatively fragile at this time, because when the last file is closed, if the first man_file.close () execution is incorrect, the second other_file.close () will not be executed, in this case, other_file fails to be closed. At this time, we can use the finally statement to limit it. With the finally extension try, we can place the data close operation directly in the finally statement for the operation as follows:
man= []other = []try:    data = open('sketch.txt')    for each_line in data:        try:            (role,line_spoken) = each_line.split(":",1)            line_spoken = line_spoken.strip()            if role == 'Man':                man.append(line_spoken)            elif role == 'Other Man':                other.append(line_spoken)        except ValueError:            pass    data.close()except IOError:    print('The datafile is missing!')print(man)print(other)try:    man_file = open('man_data.txt','w')    other_file = open('other_data.txt','w')    print(man,file=man_file)    print(other,file=other_file)except IOError:    print('File Error')finally:    man_file.close()    other_file.close()
The running result is the same as before, and two corresponding files are generated. The difference is that the error handling capability is enhanced.
Supplement:Here we can also print the details of the error type. For example, when opening a file and reading it, We can print the details of the current error. The Code is as follows:
try:    data = open('sketch1.txt')except IOError as err:    print('File Error:'+str(err))
Here, an alias err is set for the IOError exception and the content in err is printed. Because err is an object, the str function is used to print the specific content of the object. The result is as follows:
>>> ================================ RESTART ================================>>> File Error:[Errno 2] No such file or directory: 'sketch1.txt'>>> 
In this case, the sketch1.txt file was not found.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.