Python's operations on directories require the use of built-in functions os and os.path
Contents of this chapter
3. Determine whether the directory or file exists
5. Create a multi-level directory
2. Rename files and directories
module description
os module function
function | illustrate |
getcwd() | return the current working directory |
listdir(path) | Return the file and directory information under the specified path |
mkdir(path[,mode]) | Create a directory |
makedirs(path1/path2....[,mode]) | Create multi-level directories |
rmdir(path) | delete directory |
removedirs(path1/path2) | Delete multi-level directories |
chdir(path) | Set path to the current working directory |
walk(top[,topdown[,onerror]]) | Traversing the directory tree, this method returns a tuple, including all path names, all directory lists and file lists 3 elements |
os.path module functions
function | illustrate |
abspath(path) | Used to get the absolute path of a file or directory |
exists(path) | Used to determine whether a directory or file exists, and return True if it exists, otherwise False |
join(path,name) | Concatenate directory with directory or filename |
splitext() | Separate filename and extension |
basename(path) | Extract filenames from a directory |
dirname(path) | Extract the file path from a path, excluding the filename |
isdir(path) | Used to determine whether the path is valid |
Detailed operation
1. Query the relative path
# Query the current relative path
import os
print(os.getcwd())
operation result:
2. Query the absolute path
import os
print(os.path.abspath(r"text.txt"))
operation result:
3. Determine whether the directory or file exists
exists function
Absolute or relative paths can be used
Return value: False means it does not exist True means it exists
Can determine the file or directory can be
import os
print(os.path.exists("C:\\demo"))
4. Create a directory
Note: If the specified directory has multiple levels, and the last-level upper-level directory does not exist, a FileNotFoundError exception error will be thrown, and the creation will fail. Solutions: 1. Create a multi-level directory. 2. Write a recursive function call os.mkdir function implementation, the code is as follows
os.path.split('PATH') # will be split into two tuples, one tuple is the path and the other is the created file name
1.PATH refers to the full path of a file as a parameter
2. If a directory and file name are given, output the path and file name
3. If a directory name is given, the output path and file name are empty
import os # 导入函数
def mkdir_file(path): # 定义递归创建目录函数
if not os.path.exists(path): # 判断是否为有效路径
mkdir_file(os.path.split(path)[0]) # 递归函数调用
else: # 目录存在则直接返回
return
os.mkdir(path) # 创建目录
mkdir_file("D:\\test\\文件操作\\test") # 调用mkdir()递归函数
# 注意 要用 \ 转义一下
5. Create a multi-level directory
os.mkdir creates a first-level directory os.makedirs is used to create directories recursively
Format:
os.makedirs(file_name,mode=0o777)
Parameter Description:
file_name : used to specify the directory to be created, you can use an absolute path or a relative path
mode: used to specify the numerical mode, the default is 0o777. This parameter is invalid or ignored on non-UNIX systems
usage:
import os
os.makedirs("D:\\test\dir\test\test") # 创建多级目录
6. Delete directory
Use the os.rmdir() function to delete a directory. Note that only empty directories can be deleted here. If you want to delete a directory with content, you need to use the built-in function shutil. Two ways of writing are shown below
import os
os.rmdir("D:\\test\test") # 删除空目录 “\”转义
import shutil
shutil.rmtree("D:\\test") # 删除非空目录
7. Traversing directories
Traversing a directory is to display all the directories under the specified directory, including subdirectories, files, etc. In the os module, the walk function is used to realize the function of traversing the directory and return it in the form of a tuple.
Format:
os.walk(top,[topdown],[onerror],[followlinks])
Parameter Description:
top: used to specify the root directory to traverse the content
topdown: optional parameter, used to specify the order of traversal, if the value is True means top-down False means bottom-up
onerror: The optional parameter is used to specify the error handling method, and the default is ignored. If you don’t want to ignore it, you can specify an error handling function, usually using the default
followlinks: optional parameter. By default, the walk function will not turn down into a symbolic link resolved to the directory. Change the parameter to True, indicating that it is used to specify to access the target pointed by the symbolic link on the supported system.
# example
import os
file = os.walk("test") # 遍历当前目录下的test目录
for i in file: # 循环 遍历的目录 直接打印 遍历的目录是出不来的
print(i)
operation result:
Advanced File Operations
File-related functions and descriptions provided by the os module
function | illustrate |
access(path,accessmode) | Get whether the file has the specified access permissions (read, write, execute). The value of accessmode is R_OK (read), W_OK (write), X_OK (execute), F_OK (exist). Returns 1 if no permissions specified, 0 otherwise |
chmod(path,mode) | Modify file access permissions |
remove(path) | Delete the file path specified by path |
rename(src,dst) | Rename the file or directory src to dst |
stat(path) | Return information about the file specified by path |
startfile(path,[operation]) |
Open the file specified by path with the associated application |
1. Delete files
import os
os.remove("test.txt") # 删除文件test.txt 可以加路径但是要加 转义字符“\”
2. Rename files and directories
import os
# 修改文件
src = "test\\01\\TEST.txt" # 要修改的文件名称
dst = "test\\01\\Test.txt" # 修改后的文件名称
os.rename(src, dst) # 执行修改 先是要修改的文件名称 然后是修改的文件名称
# 修改目录
catalog = "test\\01" # 要修改的目录名称
catalog1 = "test\\66" # 修改后的目录名称
os.rename(catalog,catalog1)
Get basic file information
The os.stat function is used to obtain basic file information (file size, last access time, last modification time, last status change time, index number, device name) and other information. Note: format conversion is required to become intuitive
property description
Attributes | illustrate |
st_mode | protected mode |
st_dev | Equipment name |
st_ino | The index number |
st_nlink | Hard link number (number of links) |
st_size | file size in bytes |
st_mtime | last modified time |
st_uid | User ID |
st_gid | group ID number |
st_atime | last visit time |
st_ctime | The time of the last state change. Different systems return different results. For example, under windows, the file creation time is returned |
# Example:
Display file index number, device number, file size, last access time, last modification time, last status change time
Comparison of the two ways of demonstrating conversion and non-conversion
import os
fileinfo = os.stat("test\\02\\test.txt")
# 输出文件的基本信息
print("未转换显示内容".center(50, "-"))
print("索引号:", fileinfo.st_ino)
print("设备名:", fileinfo.st_dev)
print("文件大小:", fileinfo.st_size, "B")
print("最后一次访问时间:", fileinfo.st_atime)
print("最后一次修改时间:", fileinfo.st_mtime)
print("最后一次状态变化时间:", fileinfo.st_ctime)
import time
def FormatTaime(longtime):
"""
格式化日期的函数
logtime:要格式化的时间
"""
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(longtime)) # 导入时间模块 并以 年月日 时分秒的形式显示
def formatByte(number):
"""
格式化文件大小的函数
number:要格式化的字节数
"""
for (scale, labei) in [(1024 * 1024 * 1024, "GB"), (1024 * 1024 * 1024, "MB"), (1024, "KB")]:
# scale 第一次循环为 :1,073,741,824 labei 第一次循环结果为:GB
if number >= scale: # 如果文件大小 大于 等于 1KB
return "%.2f %s" % (number * 1.0 / scale, labei) # %.2f :格式化输出
elif number == 1: # 如果文件小于1B
return "1 B"
else: # 处理小于1b的文件
byte = "%.2f" % (number or 0)
return (byte[:-3] if byte.endswith('.00') else byte) + "B"
print("已转换显示内容".center(50, "-"))
print("索引号:", fileinfo.st_ino)
print("设备名:", fileinfo.st_dev)
print("文件大小:", formatByte(fileinfo.st_size))
print("最后一次访问时间:", FormatTaime(fileinfo.st_atime))
print("最后一次修改时间:", FormatTaime(fileinfo.st_mtime))
print("最后一次状态变化时间:", FormatTaime(fileinfo.st_ctime))
operation result: