python中的path的使用

https://blog.csdn.net/pz789as/article/details/105684141

直接上代码:


   
   
  1. # 使用 pathlib 中的 Path,对于路径拼接,拆分等操作都能很好的支持
  2. test_path = Path( '/Users/xxx/Desktop/project/data/')
  3. file_name = 'hello_game_LevelUp.csv'
  4. file_path = test_path/file_name # 直接使用斜杆拼接路径即可
  5. file_path_na = test_path/ 'no find.txt' #不存在的文件
  6. print( '目标路径:', test_path)
  7. print( '')
  8. print( '拼接文件名:', file_path)
  9. print( '')
  10. print( '路径最后的文件或路径名称:', test_path.name, file_path.name)
  11. print( '')
  12. print( '判断文件或路径是否存在:', test_path.exists(), file_path.exists(), file_path_na.exists())
  13. print( '')
  14. print( '路径根目录:', test_path.root, test_path.home())
  15. print( '')
  16. print( '排除后缀名的文件或路径名:', test_path.stem, file_path.stem)
  17. print( '')
  18. print( '文件的后缀名:', test_path.suffix, file_path.suffix)
  19. print( '')
  20. print( '是否为路径:', test_path.is_dir(), file_path.is_dir())
  21. print( '')
  22. print( '是否为文件:', test_path.is_file(), file_path.is_file())
  23. print( '')
  24. print( '当前路径或文件的父目录:', test_path.parent, file_path.parent)
  25. print( '')
  26. print( '父目录可以继续调用父目录:', test_path.parent.parent, test_path.parent.parent.parent.parent)
  27. print( '')
  28. new_path = test_path/ 'new_path'/ 'new_path'
  29. if new_path.exists():
  30. print( '路径存在,删除路径:', new_path.rmdir()) # 删除只能删除空文件夹,需要遍历目录
  31. else:
  32. print( '路径不存在,创建路径:', new_path.mkdir(parents= True)) # 参数 parents 表示如果父目录不存在,是否要创建父目录
  33. print( '')
  34. print( '遍历目录:', test_path)
  35. files = test_path.glob( '*.xlsx') # 可以匹配类型
  36. for f in files:
  37. print(f)
  38. print( '')

可以把路径改了,弄个文件,测试一下就能一目了然了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值