Learn python series from zero to read and save data from files

  • 2020-04-02 13:42:20
  • OfStack

Download all the files from the HeadFirstPython website. After unzip, take "sketch. TXT" in chapter 3 as an example:

 

Create a new IDLE session, import the OS module first, and change the working directory to a folder containing the file "sketch. TXT", such as C:\ Python33\ HeadFirstPython\ chapter3


>>> import os
>>> os.getcwd()    # View the current working directory 
'C:\Python33'
>>> os.chdir('C:/Python33/HeadFirstPython/chapter3')   # Switch folders that contain data files 
>>> os.getcwd()     # View the working directory after the switch 
'C:\Python33\HeadFirstPython\chapter3'

Open the file "sketch. TXT", read and display the first two lines:


>>> data=open('sketch.txt')
>>> print(data.readline(),end='')
Man: Is this the right room for an argument?
>>> print(data.readline(),end='')
Other Man: I've told you once.

Go back to the beginning of the file, use the for statement to process each line in the file, and finally close the file:


>>> data.seek(0)   # use seek() Method returns to the start of the file 
>>> for each_line in data:
    print(each_line,end='')
    
Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!
>>> data.close()

After reading the file, save the corresponding data of different roles to the list man and other respectively:


import os
print(os.getcwd())
os.chdir('C:Python33HeadFirstPythonchapter3')
man=[]    # Define a list man receive Man The content of the 
other=[]  # Define a list other receive Other Man The content of the 
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)

Tips:

When using the open() method to open a disk file, the default access mode is r, meaning read.

To open a file for writing, specify the mode w, such as data=open("sketch.txt","w").

To append to a file, specify mode a and do not empty existing content.

To open a file for writing and reading without emptying existing content, specify the mode w+;

  For example, when the man and other contents saved in the previous example are saved as files, the following changes can be made:


import os
print(os.getcwd())
os.chdir('C:Python33HeadFirstPythonchapter3')
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!')
try:
    man_file=open('man.txt', 'w')      # In order to w Mode access file man.txt
    other_file=open('other.txt','w')   # In order to w Mode access file other.txt
    print (man, file=man_file)           # Will list man Is written to the file 
    print (other, file=other_file)
except IOError:
    print ('File error')
finally:
    man_file.close()
    other_file.close()

But why did print() on line 26 report an error? "Syntax error while detecting the tuple", there is a great god can give to reassure the no


Related articles: