Python learning notes (novice introduction) file operation and time operation

Posted by jsschmitt on Mon, 03 Jan 2022 08:41:14 +0100

catalogue

4.1 time and date

4.1.1 time module

4.1.2 Sleep function

4.1. 2. Datetime module

4.1.2.1 now() method

4.1. 2.2 strftime (FMT) method

4.2 document operation

4.2. 1 open file

4.2. 2 write file

4.2.2.1 write() method

4.2.2.2 writelines() method

4.2. 3 read file

4.2.3.1 read() method

4.2.3.2 readlines() method

4.2.3.3 with keyword

4.2. 4 document management

4.2.4.1 rename(oldfile,newfile) function

4.2.4.2 remove(path) function

4.2.4.3 mkdir() function

4.2.4.4 getcwd function

4.2.4.5 listdir(path) function

4.2.4.6 rmdir(path) function

4.2. 5 file location

4.2.5.1 tell() function

4.2.5.2 seek(offset,from) function

4.1 time and date

In Python, date and time are often used. Python provides rich time and date modules and functions, such as time

datetime and other modules.

4.1.1 time module

Some functions related to world processing and conversion are defined in Python's built-in time module. Next, let's introduce them to you

 import time
 # Get current time
 print(time.time())
 # The lacaltime function obtains local time information
 date_time = time.localtime()
 print(date_time)

4.1.2 Sleep function

sleep can pause for a few seconds while the function is running

 for t in range(3,-1,-1):
     print("count down:",t)
     if t != 0:
         time.sleep(1)
         pass
     else:
         print("Go!")

4.1. 2. Datetime module

The datetime module provides richer functions related to date and time processing, which is more advanced than the functions provided by the time module.

4.1.2.1 now() method

Get current date and time

 import datetime
 # Get current date and time
 current_time = datetime.datetime.now()
 print("Default format:{}".format(current_time)) # Get current date and time
 print("year:",current_time.year) # Get current year
 print("month:",current_time.month) # Get current month
 print("day:",current_time.day) # Get current day
 print("hour",current_time.hour) # Get current hour
 print("minuth:",current_time.minute) # Gets the current minute
 print("second:",current_time.second) # Gets the current number of seconds 

4.1. 2.2 strftime (FMT) method

Format the date and time according to the custom formatting method. The function needs to pass in an fmt parameter, which is composed of time formatting symbols.

 import datetime
 #Custom date time formatting
 format_time = datetime.datetime.now().strftime("%Y/%m/%d  %H:%M:%S")
 print("Custom format:{}".format(format_time))

4.2 document operation

In the daily process of program development, we often need to use file operation. Python has built-in functions related to operating files, which makes operating files very simple.

4.2. 1 open file

 # Open file
 fobj=open("./test.txt","w",encoding="utf-8") # Open the test file in the default py environment
 # open("test.txt1","r") #If there is no such file, an error will be reported
Open modeMode description
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode
wOpen a file for writing. If the file already exists, overwrite it. If the file does not exist, create a new file
aOpen a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing
rbOpen a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode
wbOpen a file in binary format for writing only. If the file already exists, overwrite it. If it does not exist, a new file will be created
abOpen a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file
w+Open a file for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file is opened in append mode. If the file does not exist, create a new file for reading and writing
rb+Open a file in binary format for reading and writing, and the file pointer will be placed at the beginning of the file
wb+Open a file in binary format for reading and writing. If the file already exists, overwrite it. If it does not exist, create a new file
ab+Open a package in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing

Binary reading is mainly used to read pictures, videos and audio. Normal text does not need binary reading. At the same time, pay attention to coding. The default is gbk

4.2. 2 write file

4.2.2.1 write() method

Only one string can be written to a file by calling the write() method at a time.

 fobj=open("./test.txt","a",encoding="utf-8")
 fobj.write("\n Hello, Python") # Append after file
 fobj.close() # Close the file. After writing the file, you must close the file.

4.2.2.2 writelines() method

writelines() supports writing multiple strings in a sequence to a file at once.

 fobj=open("./test.txt","a",encoding="utf-8") #Specify the file, append after the file, and specify the format utf-8
 fobj.writelines(["Hello, Python","\n Hello, World","\n Hello, Pycharm"]) # Append after file
 fobj.close() # Close the file. After writing the file, you must close the file.

4.2. 3 read file

4.2.3.1 read() method

Read the data from the file. The read() method can read all the contents of the file at once

 f = open("test.txt","r",encoding="utf-8")
 print(f.read()) # Read all contents of the file at one time
 print(f.read(5)) # Read 5 characters in the file
 fobj.close() # Close the file. After writing the file, you must close the file.

4.2.3.2 readlines() method

The readlines() method reads out all the items in the whole file at one time in the form of lines. The returned result is a list, and a line of data in the file is an element in the list.

 f = open("test.txt","r",encoding="utf-8")
 print(f.readlines()) # Read all the contents of the file at one time and return a list
 fobj.close() # Close the file. After writing the file, you must close the file.

4.2.3.3 with keyword

After writing a file, the file object usually closes the file through the close method. In addition, Python provides a safe way to open files, that is, using with with open, so you don't need to close files, and it's also convenient for the computer to save memory.

 with open("test.txt","a",encoding="utf-8") as f:
     f.writelines("Hello, Python") # Append after file

4.2. 4 document management

4.2.4.1 rename(oldfile,newfile) function

Python's built-in rename function is used to rename files or folders. Note: if the folder or file to be operated does not exist, the rename function will report an error

 import os
 os.rename("test.txt","test.txt")

4.2.4.2 remove(path) function

Python's built-in remove function is used to delete the specified file. If there is no absolute path to the file, the file will be found under the relative path

 import os
 os.remove("test.txt")

4.2.4.3 mkdir() function

Python's built-in mkdir function can create a folder under the specified path

 import os
 os.mkdir("c://Program File//test")

4.2.4.4 getcwd function

Python's built-in getcwd function is used to obtain the absolute path of program operation

 import os
 print(os.getcwd())

4.2.4.5 listdir(path) function

Python's built-in listdir function is used to obtain the absolute path of program operation

 import os
 lsdir = os.listdir("./")
 print(lsdir)

4.2.4.6 rmdir(path) function

Python's built-in rmdir function is used to delete the empty folder under the specified path. If it is not empty, the program will report an error.

 import os
 os.rmdir("./dates")

4.2. 5 file location

4.2.5.1 tell() function

Function positioning refers to the position read by the current file pointer and the cursor position. In the process of reading the file, if you want to know the location of the file, you can use tell() to get it.

 with open("test.txt","r") as f:
     print(f.read(3)) # Read the characters of the file
     print(f.tell()) # Check where the pointer is. Note: one Chinese character accounts for two characters

4.2.5.2 seek(offset,from) function

If you need to navigate to another location during file operation, use the seek function

Offset offset is in bytes. A negative number is a backward offset and a positive number is a forward offset,

from position, 0 indicates the beginning of the file, 1 indicates the current position, and 2 indicates the end of the file

 with open("test.txt","rb") as f:
     f.seek(-2,2) # The cursor moves back two bytes at the end
     print(f.read(4))

Topics: Python Back-end