当前位置:网站首页>Common system modules and file operations
Common system modules and file operations
2022-07-04 10:39:00 【She was your flaw】
Common system modules and file operations
One 、time modular
- Time stamp
Use the specified time to 1970 year 1 month 1 Japan 0 when 0 second ( Greenwich mean time ) The time difference ( The unit is seconds ) The way to express time is timestamp
Be careful : Greenwich mean time and Beijing time are 8 Hour time difference
4 Bytes ( Timestamp storage time )
16 Bytes ( Use string to store time )
import time
1. time.time() -- Get the current time
print(time.time()) # 1627612143.562589
2.
time.localtime() -- Get the local time of the current time , Returns the structure time
time.localtime( Time stamp ) -- Convert the time corresponding to the timestamp into local time
t1 = time.localtime()
print(time.localtime(1627612143.562589))
print(time.localtime(0))
3. time.sleep( Time ) -- Program hibernate for a specified time , Unit second
time.sleep(2)
print('==========')
time.strftime( Time format , Structure time ) Structure time to string time
xxx year xx month xx Japan xx when :xx branch :xx second
‘’’
%Y - year
%m - month
%d - Japan
%H - when (24 Hours )
%I - when (12 Hours )
%M - branch
%S - second
%p - AM、PM( In the morning 、 Afternoon )
%a - Abbreviations of English words of week
%A - Spelling English words on Sunday
%b - English abbreviation of month
%B - Month English spelling
‘’’
result = time.strftime('%Y year %m month %d Japan %H:%M:%S', t1)
print(result)
# xxxx-xx-xx xx:xx:xx
result = time.strftime('%Y-%m-%d %H:%M:%S', t1)
print(result)
result = time.strftime('%m month %d Japan %p%I:%M %B', t1)
print(result)
- Convert string time to structure time
time.strptime( String time , Time format )
t2 = '2010-10-2'
t3 = time.strptime('2010-10-2', '%Y-%m-%d')
print(f' Zhou {
t3.tm_wday+1}')
print(t3)
6. Convert string time to timestamp ( First convert the string time into the structure time )
time.mktime( Structure time ) -- Convert structure time to timestamp
result = time.mktime(t3)
print(result)
Two 、datetime modular
import datetime
from datetime import datetime
- datetime type – Processing time including year, month, day, hour, minute and second
1) establish datetime Time object
datetime(year,moth,day, hour=0, minute=0, second=0)
t1 = datetime(2010, 10, 2)
print(t1) # 2010-10-02 00:00:00
t2 = datetime(2011, 9, 30, 11, 15, 30)
print(t2) # 2011-09-30 11:15:30
2) Get time attribute
Time object .year、 Time object .month、…
print(t2.month)
print(t2.hour)
- Get the current time
t3 = datetime.now()
print(t3)
- take datetime Convert to structure time
t4 = t3.timetuple()
print(t4)
- take datetime Convert to string time
st5 = t3.strftime('%Y year %m month %d Japan %a')
print(st5)
- Convert string time to datetime
st6 = '2003-7-1'
t5 = datetime.strptime(st6, '%Y-%m-%d')
print(t5)
2.timedelta - It is mainly used for time addition and subtraction
from datetime import timedelta
t6 = t5 + timedelta(days=45)
print(t6)
t7 = t5 - timedelta(hours=8)
print(t7)
t8 = t5 + timedelta(days=1, hours=5, minutes=15)
print(t8)
3、 ... and 、hashlib modular
import hashlib
# hashlib modular - For generating data hash Abstract
‘’’
hash Encryption algorithms mainly include :md5 and shaxxx
hash Features of encryption :
a. Irreversible ( After encrypting the original data ( Generated summary ) Unable to restore )
b. The same data is generated by the same algorithm ( Ciphertext ) It's the same
c. Data of different sizes have the same length of summaries generated by the same algorithmUse hashlib Generate a summary of the data
‘’’- Create according to the algorithm hash object
hashlib. Algorithm name ()
hash = hashlib.md5()
2. Add data
hash object .update( binary data )
pw = '123456'
hash.update(pw.encode())
f = open('files/text.py', 'rb')
hash.update(f.read())
3. Get a summary
result = hash.hexdigest()
print(result)
‘’’
python Binary data type – bytes
String and bytes Mutual conversion of
str --> bytes
Method 1 :bytes( character string , ‘utf-8’)
Method 2 :b’ character string ’
Method 3 : character string .encode()bytes --> str
Method 1 :str( binary data , ‘utf-8’)
Method 2 : Binary system .decode()
‘’’
# String to binary
print(bytes('abc', 'utf-8')) # b'abc'
b1 = b'abc'
print(type(b1)) # <class 'bytes'>
str1 = 'abc'
print(str1.encode())
# Binary to string
print(str(b1, 'utf-8'))
print(b1.decode())
Four 、 File operations
- Data storage
‘’’
The data saved in the program is stored in the running memory by default , The data in the running memory will be released at the end of the program .
If you want the data generated during the operation of the program not to be destroyed after the end of the program , You need to store data on disk .
The process of storing data to disk is called data persistence 、 Data localization .
The basic principle of data persistence - Store data on disk through files .
‘’’
File operations ( Operation file content )
‘’’
File operation mainly solves two problems :a. How to store the data in the program to disk through files
b. How to use the data saved in the file in the program
‘’’Basic steps of file operation
‘’’
First step : Open file
open( File path , Read write mode ,encoding= File encoding ) – Open the specified file in the specified way , Return file object
1) File path – Location information of the file in the computer , Provide values as strings .
a. Absolute path : The full path of the file in the computer
b. Relative paths :. – Represents the current directory ( The directory where the current code file is located ),./ It can be omitted
… – Represents the upper directory of the current directory
Read write mode – Set whether the read operation or write operation is supported after opening the file ; Set whether the type of operation data is string or binary
The first set of values :
r – read-only
w – Just write ; Clear the original file first
a – Just write ; Keep the contents of the original file , Add data to the back
Second set of values :
t – The data type is string (t You can ignore )
b – The data type is bytes'r' == 'rt' == 'tr'
Be careful : If it is a text file, you can use t perhaps b The way to open , If it is a binary file, you can only b The way to open
encoding – File encoding ( The encoding method of the open file must be consistent with that of the file )
With b When opening a file in the way encoding Can't assign a value
The second step : Reading documents 、 Writing documents
File object .read()
File object .write( data )
The third step : Close file
File object .close()
‘’’
Parameters 1: route
open('files/text.py')
open('../day-14 Common system modules and file operations /01-review.py')
Parameters 2: Read write mode
1) r -- read-only
f = open('test.py', 'r')
f.read()
2) w -- Just write ; Will empty the original file
f = open('test.py', 'w')
f.write('abc')
f.read()
3) t -- The type of read / write data is string
f = open('test.py', 'rt')
result = f.read()
print(type(result)) # <class 'str'>
f = open('test.py', 'at')
f.write('abc')
4) b -- The type of read-write data is binary
f = open('text.py', 'rb')
result = f.read()
print(type(result)) # <class 'bytes'>
f = open('test.py', 'ab')
f.write('abc'.encode())
f = open('02-time modular .py', mode='r', encoding='utf-8')
f.read()
f = open('files/text.py', 'r', encoding='utf-8')
f.read()
f = open(r'E:\ wallpaper \2.jpg', 'rb')
f.read()
f.close()
5、 ... and 、 Read and write operations
1. Read operations
‘’’
1)
File object .read() – Read from the read-write position to the end of the file ( The read / write location is at the beginning of the file by default )
File object .readline() – Read from the reading and writing position to the end of a line ( Only valid when reading text files )
Text object .readlines() – Line by line reading , After reading
‘’’
f = open('files/text.py', encoding='utf-8')
result = f.read()
print(result)
print('------------------- Gorgeous split line --------------------')
f.seek(0) # Set the read / write position to the beginning of the file
print(f.read())
print('------------------- Gorgeous split line --------------------')
f.seek(0)
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print('===:', f.readline(), '====', sep='')
print('------------------- Gorgeous split line --------------------')
f.seek(0)
print(f.readlines())
f.close()
print('------------------- Gorgeous split line --------------------')
f = open('test.py', 'a', encoding='utf-8')
f.write('\nabc\n123\n456')
# f.writelines(['abc', '123', '456'])
f.close()
6、 ... and 、 Data memory operation
The basic steps of data persistence :
‘’’
First step : Identify the data that needs to be persisted ( Determine which data to use the next time you run the program )
The second step : Create a file to save the initial value of data
The third step : When this data is needed in the program, read the data from the file
Step four : If the data changes , Write the latest data back to the file
‘’’
practice 1: Write a program and print the number of times the program runs
''' Run the program for the first time to print : 1 Run the program for the first time to print : 2 Run the program for the first time to print : 3 '''
f = open('count.txt', 'rt', encoding='utf-8')
count = int(f.read())
count += 1
print(count)
f = open('count.txt', 'w', encoding='utf-8')
f.write(str(count))
practice 2: Add student , And display all student information after adding ( Just need the student's name )
''' Please enter the student's name : Xiao Ming Xiao Ming [' Xiao Ming '] Please enter the student's name : floret Xiao Ming floret [' Xiao Ming ', ' floret '] Please enter the student's name :q ( Program end ) Please enter the student's name : Zhang San Xiao Ming floret Zhang San [' Xiao Ming ', ' floret ', ' Zhang San '] Please enter the student's name : Li Si Xiao Ming floret Zhang San Li Si [' Xiao Ming ', ' floret ', ' Zhang San ', ' Li Si '] Please enter the student's name :q ( Program end ) '''
demand 1:
while True:
name = input(' Please enter the student's name :')
if name == 'q':
break
f = open('count.txt', 'a', encoding='utf-8')
f.write(f'{
name} ')
f = open('count.txt', encoding='utf-8')
print(f.read())
demand 2:
while True:
name = input(' Please enter the student's name :')
if name == 'q':
break
f = open('coun1.txt', encoding='utf-8')
all_count = eval(f.read()) # '[]', "['name']"
all_count.append(name)
print(all_count)
f = open('coun1.txt', 'w', encoding='utf-8')
f.write(str(all_count))
边栏推荐
- Hlk-w801wifi connection
- Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
- On binary tree (C language)
- Introduction to tree and binary tree
- Button wizard business running learning - commodity quantity, price reminder, judgment Backpack
- Dos:disk operating system, including core startup program and command program
- For programmers, if it hurts the most...
- [Galaxy Kirin V10] [desktop] printer
- Use the data to tell you where is the most difficult province for the college entrance examination!
- Reasons and solutions for the 8-hour difference in mongodb data date display
猜你喜欢
Dichotomy search (C language)
DML statement of MySQL Foundation
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?
VLAN part of switching technology
Huge number multiplication (C language)
Reasons and solutions for the 8-hour difference in mongodb data date display
Rhcsa day 9
DCL statement of MySQL Foundation
DNS hijacking
Sword finger offer 05 (implemented in C language)
随机推荐
Sword finger offer 05 (implemented in C language)
Online troubleshooting
RHCE - day one
Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment
IPv6 comprehensive experiment
[Galaxy Kirin V10] [server] NUMA Technology
If you don't know these four caching modes, dare you say you understand caching?
What is devsecops? Definitions, processes, frameworks and best practices for 2022
MFC document view framework (relationship between classes)
[test theory] test phase analysis (unit, integration, system test)
Press the button wizard to learn how to fight monsters - identify the map, run the map, enter the gang and identify NPC
System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
Write a program to judge whether the elements contained in a vector < int> container are 9.20: exactly the same as those in a list < int> container.
Legion is a network penetration tool
Work order management system OTRs
Use C to extract all text in PDF files (support.Net core)
Communication layer of csframework
Knapsack problem and 0-1 knapsack problem
C language structure to realize simple address book
Latex error: missing delimiter (. Inserted) {\xi \left( {p,{p_q}} \right)} \right|}}