SoFunction
Updated on 2024-11-20

Learn python from scratch series of reading and saving data from files

Download all the files from the HeadFirstPython website, unzip them and use "" in chapter 3 as an example:

 

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

Copy Code The code is as follows.

>>> import os
>>> () #View the current working directory
'C:\\Python33'
>>> ('C:/Python33/HeadFirstPython/chapter3') #Switch the folder containing the data files
>>> () #View the working directory after switching
'C:\\Python33\\HeadFirstPython\\chapter3'

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

Copy Code The code is as follows.

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

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

Copy Code The code is as follows.

>>> (0) #Use the seek() method to go back to the beginning 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!
>>> ()

After reading the file, the data corresponding to the different roles are saved to the lists man and other respectively:

Copy Code The code is as follows.

import os
print(())
('C:\Python33\HeadFirstPython\chapter3')
man=[] #define the list man to receive the contents of Man
other=[] #define the list other to receive the contents of Other Man

try:
    data=open("")
    for each_line in data:
        try:
            (role, line_spoken)=each_line.split(':', 1)
            line_spoken=line_spoken.strip()
            if role=='Man':
                (line_spoken)
            elif role=='Other Man':
                (line_spoken)
        except ValueError:
                pass
    ()
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, for read, and does not need to be specified specifically;

To open a file to complete a write, specify the mode w, e.g., data=open("", "w"), which empties the existing contents if the file already exists;

To append to a file, you need to specify mode a, which does not clear the existing content;

To open a file to complete writes and reads without emptying the existing contents, you need to specify the mode w+;

For example, when saving the contents of man and other in the above example as a file, it can be modified as follows:

Copy Code The code is as follows.

import os
print(())
('C:\Python33\HeadFirstPython\chapter3')
man=[]
other=[]

try:
    data=open("")
    for each_line in data:
        try:
            (role, line_spoken)=each_line.split(':', 1)
            line_spoken=line_spoken.strip()
            if role=='Man':
                (line_spoken)
            elif role=='Other Man':
                (line_spoken)
        except ValueError:
                pass
    ()
except IOError:
    print('The datafile is missing!')

try:
man_file=open('', 'w') #Access the file in w mode
other_file=open('','w') #Access file in w mode
print (man, file=man_file) #write the contents of list man to file
    print (other, file=other_file)
except IOError:
    print ('File error')
finally:
    man_file.close()
    other_file.close()

But why does line 26 print() report an error? "syntax error while detecting tuple", can any god give a solution no?