Python-pathlib 库的 Path 用法

本文详细介绍了Python中如何进行文件路径的创建、检查和操作,包括文件名和路径的拼接、文件或路径是否存在、文件属性如后缀名和是否为文件或目录的判断等。此外,还展示了如何创建和删除文件夹,以及遍历目录查找特定类型的文件。
摘要由CSDN通过智能技术生成
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值