Python中获取当前文件的路径、当前文件所在的目录、拼接路径、当前文件的父目录、文件是否存在

前言
编写python脚本实现功能的工作中,我们常常遇到操作文件的位置问题,本文大概的列举了几种常用的方法,欢迎大家评论和补充。

获取当前文件的路径os.path.abspath(__ file __)

import os

# 可以用__file__获取当前文件的全路径
current_file_path = os.path.abspath(__file__)
print(current_file_path)
# 结果
C:\Users\admin\PycharmProjects\MyProject\Test.py

获取当前脚本文件的目录 os.path.dirname(__ file __)

import os

current_path = os.path.dirname(__file__)
print(current_path)
# 结果
C:/Users/admin/PycharmProjects/MyProject

拼接路径、获取当前文件的父目录

需进行拼接os.path.join() ,才能获取父目录

import os

pardir = os.path.pardir  # 返回 .. 表示上一层目录
current_path = os.path.dirname(__file__)
join_path = os.path.join(current_path, pardir)
father_abspath = os.path.abspath(join_path)
print("pardir: ", pardir)
print("join_path: ", join_path)
print("father_abspath: ", father_abspath)
# 结果
pardir:  ..
join_path:  C:/Users/admin/PycharmProjects/MyProject\..
father_abspath:  C:\Users\admin\PycharmProjects

文件是否存在 os.path.exists(file)

import os

file = r"C:\Users\admin\PycharmProjects\MyProject\Test.py"
if not os.path.exists(file):
    print("Does not exist!")
else:
    print("Exist! Please go on!")
# 结果
Exist! Please go on!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值