day13 package and file operations

Keywords: Python Database SQLite

Principle of import module

1. Introduction principle

When the code is executed to the import module, the system will automatically enter the specified module and execute all the codes in the module;
If the same module is imported multiple times in the same program, the corresponding code will be executed only once.

# import test
# import test
# from test import a

# from test import sum_yt
# print(f'1+2+3+...+10:{sum_yt(10)}')

from test import download
download('The Shawshank Redemption')

2. Select the executable code when importing the module

The code outside the if will be executed by other modules

if __name__ == '__main__'
	# The code in if will not be executed by other modules
	pass

Use of packages

1. What is a bag

Contain__ init__. The folder of the PY file is the package
Package name - the name of the folder (required symbol: identifier, not keyword)

2. How to use the contents of the modules in the package - how to import

1) Import package name - directly import the package (this import method is meaningless when there is no custom ___. Py file)
2) from package name, import module name 1, module name 2
3) import package name. Module name
import package name. Module name as new name
4) from package name. Module name import variable name 1, variable name 2

3. Use of init.py

import package name - what can be used through the package name is__ init__.py content

File operation

1. Data persistence

The calculated storage space is divided into two types: running memory and hard disk

  1. Characteristics of data stored in the running memory: stored when running the program, and automatically destroyed when the program runs.
    (the data in the running memory can live up to one life cycle of an application, and one data can not be used when the next program is run after being stored)
    The data used in the program is stored in the running memory by default.

  2. The characteristics of the data stored in the hard disk: it always exists until it is artificially deleted or the hard disk is damaged-- lasting
    Data persistence - stores data in the form of files on the hard disk.
    If the data generated during the program operation can be used the next time the program is run, the data needs to be persisted

2. Common persistence tools - files

Database (. db,. sqlite), excel file, csv file, json file, plist file, css file, qss file, etc

3. File operation - operation of file content

File operation steps: open file - > operate file (read, write) - > close file

3.1 opening files

open(file, mode = 'r', *, encoding=None) - open the specified file in the specified way and return a file object
1) Parameter file - determines which file to open
File - string; Path of the file to be opened (absolute path and relative path)
Absolute path: the full path (location) of the file in the computer, such as window. The path starts from the disk
Relative path: the relative path can be used only when the file to be opened is in the project directory
Use. To represent the current directory (the current directory refers to the directory where the file currently writing code is located)
Use.. to represent the upper level directory of the current directory
Absolute path
open(r '/ users / Yuting / news / Python 2106 (2) / code / 01 language foundation / day13 package and file operation / files/student.txt')

Relative path using
open('./files/student.txt')
open('files/student.txt ') # relative path start. / can be omitted

Use the relative path of
open('... / day13 package and file operations / files/student.txt')

2) Parameter mode - determines the opening mode
The value of mode determines: 1. What can be done after opening the file (read or write) 2. The type of data (string, binary) when operating the file
The value of mode consists of two sets of values:
The first set of values: can you read or write
r - read only
w - write only; The original file will be emptied
a - write only; The contents of the original file will be retained and appended
Note: if you open a nonexistent file by reading, the program will report an error. If you open a nonexistent file by writing, there will be no error, and the file will be created automatically
The second set of values: whether the data type is string or binary (the default is t)
t - string (str)
b - binary (bytes)
Note: t is used to open text files, and b is only used to open non text files

3) Parameter encoding - encoding method of text file
What encoding method is used when creating a file, and that method is used when opening it.
utf-8,gbk

Note: if you open the file in b mode, you cannot assign a value to encoding

# r - read only
# f = open('./files/student.txt', 'r')
# f.read()
# # f.write('abc')        # io.UnsupportedOperation: not writable
# w - empty the original file; Write only
# f = open('./files/student.txt', 'w')
# f.write('abc')
# # f.read()      # io.UnsupportedOperation: not readable
# a - not empty; Write only
# f = open('./files/student.txt', 'a')
# f.write('abc')
# # f.read()      # io.UnsupportedOperation: not readable
# r - there is no error in the file
# open('./files/Movie 3.txt', 'r')    # FileNotFoundError: [Errno 2] No such file or directory: './files / movie. txt'

# a. w - no error will be reported if the file does not exist, and a new file will be created
# open('./files / movie. TXT','w ')
# open('./files / Movie 2. TXT','a ')

# t - the data type is a string; b - binary data type
# f = open('./files/student.txt', 'rt')
# result = f.read()
# print(type(result))     # <class 'str'>

# f = open('./files/student.txt', 'rb')
# result = f.read()
# print(type(result))     # <class 'bytes'>


# f = open('./files/student.txt', 'at')
# f.write('abc')

# f = open('./files/student.txt', 'ab')
# f.write(b'abc')

print(type('abc'), type(b'abc'))

Supplement: conversion between binary and string

# String to binary
name = 'Xiao Ming'
result = bytes(name, encoding='utf-8')
print(result, type(result))

result = name.encode()
print(result, type(result))

# Binary to string
message = b'abc'
result = str(message, encoding='utf-8')
print(result, type(result))

result = message.decode()
print(result, type(result))

# Binary files (picture, video, audio, pdf) can only be opened with b
f = open('files/0.jpg', 'rb')
f.read()

File read / write and close

1. Read files

File object. read() - read from the read-write location to the end of the file (get the contents of the whole file)
File object. readline() - read one line (valid only for text files)

f = open('files/student.txt')
result = f.read()
print(result)

print('--------------------------------')
# f = open('files/student.txt')
f.seek(0)           # Move the read / write location to the beginning of the file
result = f.read()
print(result)

2. Write operation

File object. Write - writes data to a file
f = open('files/student.txt', 'a')
f.write('\nhello world!')

3. Close the file

File object. close()
f.close()
#f.write('\n23js')

Data persistence

1. How to achieve data persistence

Step 1: determine what data needs to be persisted
Step 2: create a file, save the data to be persisted, and determine the initial value of the file content
Step 3: when this data is needed in the program, read the data from the file
Step 4: when this data changes, the latest data must be written to the file

Exercise: write a program and print the number of times the program is executed

# Determine what data needs to be persisted: number of times
# Gets the number of last
f = open('files/count.txt')
count = int(f.read())
f.close()

# Times plus 1 before printing
count += 1
print(count)

# Writes the latest number of times to the file
f = open('files/count.txt', 'w')
f.write(str(count))
f.close()

Exercise: write an account registration function. After successful registration, print all accounts and corresponding passwords that have been registered in the current system
Enter account number: abc
Enter password: 123456
abc 123456

Input account number: Xiao Ming
Enter password: abc123
abc 123456
Xiaoming abc123

# # Data to be persisted: all registered accounts and passwords
# username = input('Please enter account: ')
# password = input('Please enter password: ')
#
# # Add the newly registered account to the file
# open('files/users.txt', 'a').write(f'{username} {password}\n')
#
# # Read out all registered accounts and passwords
# all_user = open('files/users.txt').read()
# print(all_user)

Supplement: a system function that is particularly easy to use: eval
Str (data) - converts data to a string
Eval (string) - remove the string quotation marks and get the value of the expression in the quotation marks

result = eval('100')      # 100
result = eval('12.5')     # 12.5
result = eval('[10, 20, 30]')       # [10, 20, 30]
print(result, type(result))
result = eval('{"a": 10, "b": 20}')     # {'a': 10, 'b': 20}

result = eval('10 + 20')        # 30  -> 10 + 20
print(result)

a = 100
result = eval('a * 2')   # 200   -> a * 2
print(result)

b = [10, 20, 30]
result = eval('b[-1]')     # b[-1]   -> 30
print(result)

# result = eval('abc')        # abc
# print(result)     # report errors!

Posted by twooton on Wed, 27 Oct 2021 05:05:45 -0700