author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tuto...
This paper addresses :http://www.showmeai.tech/article-detail/86
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
We're actually developing it , It is often necessary to read the file 、 Traverse 、 Modification and other operations , adopt python Standard built-in os modular , Be able to complete these operations in a concise and efficient way . Common operations are summarized as follows :
To complete the operation of files and directories , First, import the corresponding os modular , The code is as follows :
import os
Local pythontest
Directory as demo Directory , The current files in this directory are as follows :
test
│ test.txt
└─test-1
test-1.txt
test
And test-1
It's a folder. ,test.txt
And test-1.txt
It's a document .
stay linux We use ls
/ pwd
/ cd
Wait to complete operations such as querying and switching paths , Corresponding python The operation method is as follows :
>>> os.chdir("./pythontest") # Change directory
>>> os.getcwd() # Get current directory
'/Users/ShowMeAI/pythontest'
>>> os.listdir("test") # List of files and directories , Relative paths
['test-1', 'test.txt']
>>> os.listdir("/Users/ShowMeAI/test") # List of files and directories , Absolute path
['test-1', 'test.txt']
>>> os.stat("test") # Get directory information
os.stat_result(st_mode=16877, st_ino=45805684, st_dev=16777221, st_nlink=11, st_uid=501, st_gid=20, st_size=352, st_atime=1634735551, st_mtime=1634735551, st_ctime=1634735551)
>>> os.stat("test/test.txt") # Get file information
os.stat_result(st_mode=33188, st_ino=45812567, st_dev=16777221, st_nlink=1, st_uid=501, st_gid=20, st_size=179311, st_atime=1634699986, st_mtime=1634699966, st_ctime=1634699984)
among stat The function returns the basic information of the file or directory , As follows :
In daily use , We usually use st_size 、st_ctime And st_mtime Get file size , Creation time , Modification time . in addition , We see that the output time is seconds , Let's talk about , About date conversion processing .
walk Function to recursively traverse the directory , return root,dirs,files, Corresponding to the current traversal directory , Subdirectories and files in this directory .
data = os.walk("test") # Traverse test Catalog
for root,dirs,files in data: # Recursive traversal and output
print("root:%s" % root)
for dir in dirs:
print(os.path.join(root,dir))
for file in files:
print(os.path.join(root,file))
>>> os.mkdir("new")
>>> os.mkdir("new1/new1-1") # Parent directory does not exist , Report errors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: The system could not find the specified path .: 'new1/new1-1'
>>> os.makedirs("new1/new1-1") # Parent directory does not exist , Automatically create
>>> os.listdir("new1")
['new1-1']
>>> os.rmdir("new1") # If the directory is not empty , Report errors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: The directory is not empty .: 'new1'
>>> os.rmdir("new1/new1-1")
>>> os.removedirs("new1/new1-1") # Delete multi-level empty directory
>>> os.listdir(".")
['new']
Due to the restriction of deleting empty directories , It's more about use shutil
Module rmtree
function , You can delete non empty directories and their files .
>>> os.makedirs("new1/new1-1")
>>> os.rename("new1/new1-1","new1/new1-2") # new1-1 new1-2
>>> os.listdir("new1")
['new1-2']
>>> os.rename("new1/new1-2","new2/new2-2") # because new2 directory does not exist , Report errors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: The system could not find the specified path .: 'new1/new1-2' -> 'new2/new2-2'
>>> os.renames("new1/new1-2","new2/new2-2") # renames Can automatically create non-existent directories
>>> os.listdir("new2")
['new2-2']
If the destination path file already exists , that os.rename() and os.renames() All will report wrong. :FileExistsError, When the file already exists , Unable to create the file .
>>> f = os.open("test/test.txt", os.O_RDWR|os.O_CREAT) # Open file
>>> str_bytes = os.read(f,100) # read 100 byte
>>> str = bytes.decode(str_bytes) # Byte to string
>>> print(str)
test write data
>>> os.close(f) # Close file
Be careful open/read/close Need to operate together , among open The operation needs to specify the mode , The above is to open the file in read-write mode , If the file does not exist, create the file . The specific modes are as follows :
flags -- This parameter can be the following options , Multiple uses "|" separate :
Use open create a file , Specify the mode , If the file does not exist , Create . It's kind of similar linux In operation touch.
>>> f = os.open("test/ShowMeAI.txt", os.O_RDWR|os.O_CREAT) # If the file does not exist , Create
>>> os.close(f)
>>> f = os.open("test/ShowMeAI.txt", os.O_RDWR|os.O_CREAT) # Open file
>>> os.write(f,b"ShowMeAI test write data") # Write content
15
>>> os.close(f) # Close file
>>> os.remove("test/test-1") # Error in deleting Directory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: The system cannot find the specified file .: 'test/test1'
>>> os.remove("test/ShowMeAI.txt") # Delete file
>>> os.listdir("test")
['test-1']
In the process of using files or directories , It is often necessary to deal with files and directory paths , therefore ,os There is a sub module in path, It is dedicated to processing path operations . The main operations are as follows :
>>> os.path.abspath("test")
'/Users/ShowMeAI/test'
>>> os.path.exists("test")
True
>>> os.path.exists("test/test.txt")
False
>>> os.path.exists("test/test-1/test-1.txt")
True
>>> os.path.isdir("test")
True
>>> os.path.isfile("test/test-1/test-1.txt")
True
/
For the separator , Divided into head (head) And tail (tail) Two parts ,tail yes basename What's coming back ,head yes dirname What's coming back . Often used to get file names , Directory name and other operations >>> os.path.basename("test/test-1/test-1.txt") # file name
'test-1.txt'
>>> os.path.basename("test/test-1/") # Empty content
''
>>> os.path.basename("test/test-1") # Directory name
'test-1'
>>> os.path.dirname("test/test-1/test-1.txt") # The path to the directory where the file is located
'test/test-1'
>>> os.path.dirname("test/test-1/") # Directory path
'test/test-1'
>>> os.path.dirname("test/test-1") # Parent directory path
'test'
>>> os.path.join("test","test-1") # Connect two directories
'test/test-1'
>>> os.path.join("test/test-1","test-1.txt") # Connect directory and filename
'test/test-1/test-1.txt'
>>> os.path.split("test/test-1") # Split Directory
('test', 'test-1')
>>> os.path.split("test/test-1/") # With / The end of the directory partition
('test/test-1', '')
>>> os.path.split("test/test-1/test-1.txt") # Split file
('test/test-1', 'test-1.txt')
>>> os.path.splitext("test/test-1")
('test/test-1', '')
>>> os.path.splitext("test/test-1/")
('test/test-1/', '')
>>> os.path.splitext("test/test-1/test-1.txt") # Distinguish between file name and extension
('test/test-1/test-1', '.txt')
>>> os.path.splitext("test/test-1/test-1.txt.mp4") # With the last "." For the point of division
('test/test-1/test-1.txt', '.mp4')
def batch_rename(dir_path):
itemlist = os.listdir(dir_path)
# Get the list of catalog files
for item in itemlist:
# Connect into a full path
item_path = os.path.join(dir_path, item)
print(item_path)
# Change file name
if os.path.isfile(item_path):
splitext = os.path.splitext(item_path)
os.rename(item_path, splitext[0] + "-ShowMeAI" + splitext[1])
def walk_ext_file(dir_path, ext_list):
# @dir_path Parameters : Traversal directory
# @ext_list Parameters : Extended name list , example ['.mp4', '.mkv', '.flv']
# Traverse
for root, dirs, files in os.walk(dir_path):
# Get the file name and path
for file in files:
file_path = os.path.join(root, file)
file_item = os.path.splitext(file_path)
# Output the file path with the specified extension
if file_item[1] in ext_list:
print(file_path)
def sort_file_accord_to_time(dir_path):
# Before ordering
itemlist = os.listdir(dir_path)
print(itemlist)
# Forward order
itemlist.sort(key=lambda filename: os.path.getmtime(os.path.join(dir_path, filename)))
print(itemlist)
# Reverse sorting
itemlist.sort(key=lambda filename: os.path.getmtime(os.path.join(dir_path, filename)), reverse=True)
print(itemlist)
# Get the latest modified file
print(itemlist[0])
Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition
https://www.bilibili.com/vide...
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can surf the Internet scientifically can also use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :