test_path = Path('/Users/xxx/Desktop/project/data/')
file_name = 'hello_game_LevelUp.csv'
file_path = test_path/file_name # 直接使用斜杆拼接路径即可
file_path_na = test_path/'no find.txt' #不存在的文件
print('目标路径:', test_path) #目标路径: \Users\xxx\Desktop\project\data
print('拼接文件名:', file_path) #拼接文件名: \Users\xxx\Desktop\project\data\hello_game_LevelUp.csv
print('路径最后的文件或路径名称:', test_path.name, file_path.name) #路径最后的文件或路径名称: data hello_game_LevelUp.csv
print('判断文件或路径是否存在:', test_path.exists(), file_path.exists(), file_path_na.exists()) #判断文件或路径是否存在: False False False
print('路径根目录:', test_path.root, test_path.home()) #路径根目录: \ C:\Users\Administrator
print('排除后缀名的文件或路径名:', test_path.stem, file_path.stem) #排除后缀名的文件或路径名: data hello_game_LevelUp
print('文件的后缀名:', test_path.suffix, file_path.suffix) #文件的后缀名: .csv
print('是否为路径:', test_path.is_dir(), file_path.is_dir()) #是否为路径: False False
print('是否为文件:', test_path.is_file(), file_path.is_file()) #是否为文件: False False
print('当前路径或文件的父目录:', test_path.parent, file_path.parent) #当前路径或文件的父目录: \Users\xxx\Desktop\project \Users\xxx\Desktop\project\data
print('父目录可以继续调用父目录:', test_path.parent.parent, test_path.parent.parent.parent.parent) #父目录可以继续调用父目录: \Users\xxx\Desktop \Users
new_path = test_path/'new_path'/'new_path'
if new_path.exists():
print('路径存在,删除路径:', new_path.rmdir()) # 删除只能删除空文件夹,需要遍历目录
else:
print('路径不存在,创建路径:', new_path.mkdir(parents=True)) # 参数 parents 表示如果父目录不存在,是否要创建父目录
#路径不存在,创建路径: None
print('遍历目录:', test_path) #遍历目录: \Users\xxx\Desktop\project\data
files = test_path.glob('*.xlsx') # 可以匹配类型
for f in files:
print(f) #
原文链接:https://blog.csdn.net/pz789as/article/details/105684141