Pyf20230323 (Python file operation)

01 Data Storage

1. Computer data storage

Computer memory is divided into two types: running content and hard disk: the data stored in the running memory will be released automatically after the program runs
The data saved in the hard disk will always exist (unless manually deleted or the hard disk is damaged)

2. Data persistence

Data persistence is also called data localization, which refers to saving the data in the program on the hard disk (the data in the program is saved in the running memory by default).
The basic unit of storing data on a hard disk is a file, so if you want to save data to the hard disk, you need to save the data to a file.
Common data persistence: database (.db, .sqlite), excel file, csv file, txt file

3. File operations – manipulate file content

Basic steps of file operation: open file -> operate file content (read operation, write operation) -> close file

3.1 Open file

Open method 1:
open(file path, file open method=’r’, encoding=text file encoding method)
Open method 2:
with open(file path, open method, encoding=text file encoding method) as file object:
code block

1) File path – the location information of the file in the computer
a. Absolute path: the full path of the file in the computer
b. Relative path: When using a relative path, generally put the file into the project directory first. Use ‘.’ to indicate the current directory, and use ‘…’ to indicate the upper directory of the current directory
Note: When the path starts with ‘./’, ‘./ can be omitted’

# absolute path
# open(r'E:\Workspace Python\Py20230214 (Python operates excel xlsx format file)\files\example.xlsx')

# relative path
# open(r'.\files\student information.xlsx')

2) File opening method – determines what can be done after opening the file (can it be read or written?); also determines the type of data when operating the file (is it a string or binary?)
First set of values: r – read-only (will throw an error if the file does not exist)
w – write only (will be cleared before writing)
a – write only (will append after the original content, will not clear the original content)
Second set of values:
t – string type (str, the data read and written to the file must be of string type)
b – binary type (bytes, the data read and written to the file must be binary type, and encoding cannot be used)
Note: When assigning a value to the opening method, one must be selected for each of the two sets of values. If the second set is not selected, the default is t

# # -----r is read-only-----
# f = open(r'files\data1.txt', 'r')
# f. read()
# f.write('abc') # Report an error, the original file is only readable
#
# # ----a is write-only, and will not clear the original file---
# f = open(r'files\data1.txt', 'w')
# f.write('abc')
# f.read() # Report an error, the original file can only be written
#
# # ---w is write-only, and will clear the source file
# f = open(r'files\data1.txt', 'a')
# f.write('abc')
# f.read() # Report an error, the original file can only be written
#
# # ----r Open a file that does not exist and the program reports an error! ----
# f = open(r'files\data1.txt', 'r')

# ----w and a will not report an error when opening a file that does not exist and will create the file----
# f = open(r'files\data1.txt', 'w ')
# f = open(r'files\data2.txt', 'a')
# f.write('world!')

# -------- t - data type is string ---------
# f = open(r'files\data1.txt', 'rt')
# result = f. read()
# print(type(result)) # <class 'str'>

Supplement: Common computer memory units

Minimum unit: bit (bit)
1bytes = 8bit
1kb = 1024bytes
1mb = 1024kb
1G = 1024mb
1T = 1024G

3) Requirements for the encoding method used in text file editing: consistent (the encoding value used when storing data must be consistent with the encoding value used to obtain the data) encoding method
Encoding method requirements: consistent (the encoding value used when storing data must be consistent with the encoding value used to obtain data)
Common text file encoding methods:
utf-8: a number or letter is stored in 1 byte (bytes); a Chinese is stored in 3 bytes (bytes)
gbk: a number and a letter are stored in 1 byte (bytes); a Chinese is stored in 2 bytes (bytes)
Note: Different text file encoding methods use different numbers of bytes when saving the encoding value of the same symbol

# f = open(r'files\data1.txt', 'w', encoding='utf-8')
# seq = ['1', 'haha', '2', 'abc']
# f. writelines(seq)
# f. close()

3.2 Operation file content

1. File read operation (get file content)
a. File object.read() – Get the entire file content (get the end of the file from the read and write position, and the read and write position defaults to the beginning of the file)
b. File object.readline() – read a line from the read and write position to the end
c. file object.seek(0) – move the read and write position to the beginning of the file
Note: The read operation will change the read and write position

2. File write operation (including adding content, modifying content, deleting content)
a. File object.write(content) – write the specified content to the specified file

3. Close the file
a. File object.close() – After closing the file, the file can no longer be read or written

# f = open(r'files\data1.txt', 'r', encoding='utf-8')
# f. seek(0)
# print(f. readline())
# print(f. readline())
# print(f. readline())

# Exercise: read the content of the file, read line by line, until the end of reading
# for x in f. readlines():
# print(x)

# while True:
# result = f. readline()
#print(result)
# if result == '':
#break

# iterator
# def func1():
# f1 = open(r'files\data1.txt', 'r', encoding='utf-8')
# i1 = iter(f1. readlines())
# for x in i1:
# print(x)
#
#
# func1()

# Builder
# def func2():
# while True:
# result = f. readline()
# if result == '':
#break
# yield result
#
#
# print(next(func2()))
# print(next(func2()))
# print(next(func2()))

02 Data Persistence Application

1. Data persistence method – the data generated by running the program this time can be used when the program is run next time

step1: Determine the data that needs to be persisted
step2: Create a file and determine the initial content of the file
step3: Get the data from the file when the data is needed in the program
step4: If this data changes, the latest data must be updated to the file

Example 1: Write a program to print the number of times the program runs

# def f1():
# pass
#
# def countf1(func):
# func()
#
# f = open(r'files\data2.txt', encoding='utf-8')
# count = int(f. read())
# f. close()
#
# count += 1
#print(count)
#
# f = open(r'files\data2.txt', 'w', encoding='utf-8')
# f. write(str(count))
#
# return count
#
#countf1(f1)

Exercise 1:
Please enter the name of the student to be added: Xiao Ming
Xiao Ming

Please enter the name of the student to be added: Xiaohua
Xiao Ming Xiao Hua

Please enter the name of the student to be added: Zhang San
Xiao Ming Xiao Hua Zhang San

# f = open(r'files\data3.txt', 'r', encoding='utf-8')
# name = f. read()
# f. close()

# while True:
# stu_name = input('Please enter the name of the student to be added:')
# f = open(r'files\data3.txt', 'a', encoding='utf-8')
# f.write(stu_name + ' ')
# f. close()
#
# f = open(r'files\data3.txt', 'r', encoding='utf-8')
# stu_names = f. read()
# f. close()
# print(stu_names)

Example 2:
Name: Xiao Ming
Sex: Male
Age: 18
Print: [i ’ name ’: Xiaoming’, gender’ : male’, age’ : 18}]

Name: Xiaohua
Gender: Female
Age: 20
Print: [{ ‘ name ‘: ‘Xiao Ming’, ‘gender’: ‘Male’,’age ‘: 18}, { ‘ name’: ‘Xiao Hua’, ‘gender’: ‘Female’, ‘age’: 20}-]

# need persistent data: all added student information
name, gender, age = input('Enter student name:'), input('Enter student gender:'), input('Enter student age:')
# Get all the students added before
try:
    f = open(r'files\data3.txt', encoding='utf-8')
    all_student = eval(f. read())
    f. close()
except FileNotFoundError:
    all_student = []

all_student.append({<!-- -->'name': name, 'gender': gender, 'age': age})
print(all_student)

f = open(r'files\data3.txt', 'w', encoding='utf-8')
f. write(str(all_student))
f. close()

03 Data Persistence Job

# register module
def register():
    print('xxx management system new user registration:')
    username, password = input('username:'), input('password:')

    try:
        f = open(r'files\Users.txt', encoding='utf-8')
        all_users = eval(f. read())
        f. close()
    except FileNotFoundError:
        all_users = []

    all_users.append({<!-- -->'username': username, 'password': password})

    f = open(r'files\Users.txt', 'w', encoding='utf-8')
    f.write(str(all_users))
    f. close()

    print('Successful registration!')

# login module
def login():
    print('xxx management system login')
    username, password = input('username:'), input('password:')

    f = open(r'files\Users.txt', encoding='utf-8')
    all_users = []
    all_users.append(eval(f.read()))

    for i, x in enumerate(all_users):
        if username == x[i]['username']:
            if password == x[i]['password']:
                print('Successful login!')
            else:
                print('Login failed! Password error!')
        else:
            print('Login failed! The account does not exist!')
            
    f. close()
# System login registration page
while True:
    f = open(r'files\login_page.txt', 'r', encoding='utf-8')
    login_page = f. read()
    print(login_page)

    ch = int(input('Please choose (1-3):'))

    if ch == 1:
        login()
    elif ch == 2:
        register()
    elif ch == 3:
        print('exited from xxx management system')
        break
        ```