I Data persistence
- Computer storage space is divided into two types: running memory and disk.
- The data generated in the program is saved in the running memory by default, and the data stored in the running memory will be automatically destroyed after the program is completed.
- If you store data on disk, the data will always exist unless it is manually deleted or the disk is damaged. The basic unit of data stored on disk is file.
- Data persistence refers to saving the data in the program to disk in the form of file.
- Common data persistence tools: database (. db,. sqlite), json file (. json), xml file (. xml), plist file (. plist), plain text file (. txt), excel file (. xls,. xlsx), csv file (. csv)
II File operation - operate file content
-
Basic process of file operation
Open file - > operate file (read operation, write operation) - > close file
1) Open file
open(file, mode = 'r', *, encoding = None) - open the specified file in the specified way and return a file object.
-
Parameter file - string, file path, used to determine which file to open
Absolute path: the full path of the file on the computer
Relative path: use Indicates the current directory (the current directory refers to the directory where the current code file is located)
Use... To represent the upper directory of the current directory
Note: when using relative paths, you must ensure that the files are in the project.
-
Parameter mode - string, file opening method, determines what can be done after opening the file (read or write), and determines the type of data when operating the file
(binary or string)
First set of values - determines what can be done (read or write) after opening the file
r - read only
w - write only; When it is opened, the source file will be emptied (overwritten)
a - write only; Keep the original file content when opening (append)
The second set of values - determines the type of data when operating the file
t - string (str)
b - binary (bytes)
Note: when assigning a value to mode, you must select one of the two groups of values in each group. If the second group is not selected, it is equivalent to the selected't '.
'r' == 'rt' =='tr'
'w' == 'wt' == 'tw'
'rb' == 'br'
All files can be opened in b, but only text files can be opened in t.
If you open a nonexistent file by reading, the program will report an error; Open a nonexistent file by writing. The program will not report an error and will automatically create this file.
-
Encoding - text file encoding method, which is generally set to 'utf-8' when used
Note: generally, this value does not need to be set. The default coding method is consistent with the computer default coding method.
If the file is opened in b mode, you must not assign a value to encoding.
# 1) File path open(r'/Users/yuting/lessons/Python2107/01 Language foundation/day14-File operation/files/a.txt', encoding='utf-8') open(r'./files/a.txt', encoding='utf-8') open(r'./01review.py', encoding='utf-8') open('../day14-File operation/files/a.txt') # 2) Open mode # a. r - read only # f = open('./files/a.txt', 'r') # f.read() # f.write('MAM') # io.UnsupportedOperation: not writable # b. w - write only and empty the original file # f = open('./files/a.txt', 'w') # f.write('ABC') # # f.read() # io.UnsupportedOperation: not readable # c. a - write only and retain the contents of the original file # f = open('./files/a.txt', 'a') # f.write('Hello!') # # f.read() # io.UnsupportedOperation: not readable # d. t - string # f = open('./files/a.txt', 'rt') # result = f.read() # print(type(result)) # <class 'str'> # e. b - binary # f = open('./files/a.txt', 'rb') # result = f.read() # print(type(result)) # <class 'bytes'> # open('./files/b.txt', 'r') # FileNotFoundError: [Errno 2] No such file or directory: './files/b.txt' # open('./files/c.txt', 'w') # open('./files/d.txt', 'a')
2) Operation file
-
Read operation
File object read() - read from the read-write location to the end of the file (the read-write location is at the beginning of the file by default).
File object readline() - from the reading and writing position to the end of a line (read one line at a time, only text files are supported).
f = open('files/a.txt', 'r') result = f.read() print(result) print('----------------------------------------------') f.seek(0) # Move the read / write location to the beginning of the file result = f.read() print(result) print('----------------------------------------------') f.seek(0) # result = f.readline() # print(result) # # result = f.readline() # print(result) result = f.read().split('\n') print(result)
-
Write operation
File object Write - writes the specified data to a file
f = open('./files/a.txt', 'a') nums = [10, 20, 30, 40] f.write(str(nums))
3) Close file
-
File object close()
f.close() # f.write('ahjsgdfja ') # ValueError: I/O operation on closed file. def func1(): f2 = open('files/a.txt') result = open('files/a.txt').read() print(type(result)) f = open('files/a.txt') print(type(f)) result = f.read() f.close()
-
III Data persistence method
-
Identify the data that needs to be persisted.
-
Create the appropriate file and determine the initial content of the file
-
When this data is needed in the program, it must be obtained from the file.
-
When this data is changed, the latest data must be updated to the file.
# 1. Steps of data persistence """ Step 1: identify the data to be persisted Step 2: create an appropriate file and determine the initial content of the file Step 3: when this data is needed in the program, it must be obtained from the file Step 4: when the data is changed, the latest data must be updated to the file """ # Exercise 1: write a program and print the number of times the current program runs num = int(open('files/count.txt').read()) num += 1 print(num) open('files/count.txt', 'w').write(str(num)) # Exercise 2: run the program each time, input the information of one student, and print the names of all the students that have been entered after input """ Please enter student name: Xiao Ming Xiao Ming Please enter student name: floret Xiaoming Xiaohua Please enter student name: Zhang San Xiao Ming Xiao Hua Zhang San """ # name = input('Please enter student name: ') # all_names = open('files/students.txt').read() # all_names += name + ' ' # print(all_names) # open('files/students.txt', 'a').write(f'{name} ') # Exercise 3: run the program each time, input the information of one student, and print the names of all the students that have been entered after input """ [] Please enter student name: Xiao Ming ['Xiao Ming'] Please enter student name: floret ['Xiao Ming', 'floret'] Please enter student name: Zhang San ['Xiao Ming', 'floret', 'Zhang San'] """ name = input('Please enter student name:') all_names = eval(open('files/students2.txt').read()) # type: list all_names.append(name) print(all_names) open('files/students2.txt', 'w').write(str(all_names)) # list('[]') -> ['[', ']'] # eval('[]') -> []