当前位置:网站首页>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))
边栏推荐
- /*Write a function to open the file for input, read the contents of the file into the vector container of string class 8.9: type, and store each line as an element of the container object*/
- Use the data to tell you where is the most difficult province for the college entrance examination!
- System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
- Write a program to define an array with 10 int elements, and take its position in the array as the initial value of each element.
- Collection of practical string functions
- Leetcode48. Rotate image
- [Galaxy Kirin V10] [desktop] printer
- DNS hijacking
- Quick sort (C language)
- Dos:disk operating system, including core startup program and command program
猜你喜欢
BGP advanced experiment
RHCE - day one
DDL statement of MySQL Foundation
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 2
如果不知道這4種緩存模式,敢說懂緩存嗎?
Collection of practical string functions
Rhcsa learning practice
DNS hijacking
Personal thoughts on the development of game automation protocol testing tool
Vs201 solution to failure to open source file HPP (or link library file)
随机推荐
Personal thoughts on the development of game automation protocol testing tool
Software sharing: the best PDF document conversion tool and PDF Suite Enterprise version sharing | with sharing
Introduction to extensible system architecture
Read a piece of text into the vector object, and each word is stored as an element in the vector. Convert each word in the vector object to uppercase letters. Output the converted elements in the vect
Velodyne configuration command
VI text editor and user rights management, group management and time management
【Day1】 deep-learning-basics
What is an excellent architect in my heart?
Does any teacher know how to inherit richsourcefunction custom reading Mysql to do increment?
Reprint: summation formula of proportional series and its derivation process
What is devsecops? Definitions, processes, frameworks and best practices for 2022
[Galaxy Kirin V10] [server] NUMA Technology
Error C4996 ‘WSAAsyncSelect‘: Use WSAEventSelect() instead or define _ WINSOCK_ DEPRECATED_ NO_ WARN
[Galaxy Kirin V10] [desktop] can't be started or the screen is black
Latex learning insertion number - list of filled dots, bars, numbers
Unittest+airtest+beatiulreport combine the three to make a beautiful test report
【Day2】 convolutional-neural-networks
Using Lua to realize 99 multiplication table
Today's sleep quality record 78 points
[Galaxy Kirin V10] [server] iSCSI deployment