直接上代码:
# 使用 pathlib 中的 Path,对于路径拼接,拆分等操作都能很好的支持
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)
print('')
print('拼接文件名:', file_path)
print('')
print('路径最后的文件或路径名称:', test_path.name, file_path.name)
print('')
print('判断文件或路径是否存在:', test_path.exists(), file_path.exists(), file_path_na.exists())
print('')
print('路径根目录:', test_path.root, test_path.home())
print('')
print('排除后缀名的文件或路径名:', test_path.stem, file_path.stem)
print('')
print('文件的后缀名:', test_path.suffix, file_path.suffix)
print('')
print('是否为路径:', test_path.is_dir(), file_path.is_dir())
print('')
print('是否为文件:', test_path.is_file(), file_path.is_file())
print('')
print('当前路径或文件的父目录:', test_path.parent, file_path.parent)
print('')
print('父目录可以继续调用父目录:', test_path.parent.parent, test_path.parent.parent.parent.parent)
print('')
new_path = test_path/'new_path'/'new_path'
if new_path.exists():
print('路径存在,删除路径:', new_path.rmdir()) # 删除只能删除空文件夹,需要遍历目录
else:
print('路径不存在,创建路径:', new_path.mkdir(parents=True)) # 参数 parents 表示如果父目录不存在,是否要创建父目录
print('')
print('遍历目录:', test_path)
files = test_path.glob('*.xlsx') # 可以匹配类型
for f in files:
print(f)
print('')
可以把路径改了,弄个文件,测试一下就能一目了然了