os.path相关用法
os.path相关用法
1.os.path.join(path1, path2, …)
os.path.join(path1, path2, …): 将多个路径组合成一个完整的路径。例如:
import os
path1 = "/home/user"
path2 = "documents"
full_path = os.path.join(path1, path2)
print(full_path) # 输出:/home/user/documents
2.os.path.abspath(path)
os.path.abspath(path): 返回指定路径的绝对路径。例如:
import os
path = "../documents"
abs_path = os.path.abspath(path)
print(abs_path) # 输出:/home/user/documents
3.os.path.basename(path)
os.path.basename(path): 返回指定路径中的文件名部分。例如:
import os
path = "/home/user/documents/example.txt"
filename = os.path.basename(path)
print(filename) # 输出:example.txt
4.os.path.dirname(path)
os.path.dirname(path): 返回指定路径中的目录部分。例如:
import os
path = "/home/user/documents/example.txt"
dirname = os.path.dirname(path)
print(dirname) # 输出:/home/user/documents
5.os.path.exists(path)
os.path.exists(path): 判断指定路径是否存在。例如:
import os
path = "/home/user/documents/example.txt"
if os.path.exists(path):
print("文件存在")
else:
print("文件不存在")
6.os.path.splitext(path)
os.path.splitext(path): 分离指定路径中的文件名和扩展名,并将它们以元组的形式返回。例如:
import os
path = "/home/user/documents/example.txt"
name, ext = os.path.splitext(path)
print(name) # 输出:/home/user/documents/example
print(ext) # 输出:.txt
7.os.path.isdir(path)
os.path.isdir(path): 判断指定路径是否为目录。例如:
import os
path = "/home/user/documents"
if os.path.isdir(path):
print("这是一个目录")
else:
print("这不是一个目录")
8.os.path.isfile(path)
os.path.isfile(path): 判断指定路径是否为文件。例如:
import os
path = "/home/user/documents/example.txt"
if os.path.isfile(path):
print("这是一个文件")
else:
print("这不是一个文件")
9.os.path.getsize(path)
os.path.getsize(path): 返回指定路径文件的大小(以字节为单位)。例如:
import os
path = "/home/user/documents/example.txt"
size = os.path.getsize(path)
print("文件大小为:", size, "字节")
10.os.path.getctime(path)
os.path.getctime(path): 返回指定路径文件的创建时间。例如:
import os
import time
path = "/home/user/documents/example.txt"
ctime = os.path.getctime(path)
print("文件创建时间为:", time.ctime(ctime))
11.os.path.getmtime(path)
os.path.getmtime(path): 返回指定路径文件的最后修改时间。例如:
import os
import time
path = "/home/user/documents/example.txt"
mtime = os.path.getmtime(path)
print("文件最后修改时间为:", time.ctime(mtime))
12.os.path.getatime(path)
os.path.getatime(path): 返回指定路径文件的最后访问时间。例如:
import os
import time
path = "/home/user/documents/example.txt"
atime = os.path.getatime(path)
print("文件最后访问时间为:", time.ctime(atime))