Python文件操作实用函数

文件操作

file_path=/Users/demon.li/log.txt

分割函数

print os.path.split(file_path)

Output:
('/Users/demon.li', 'log.txt')
#返回文件名
print os.path.basename(file_path)

Output:
log.txt
#返回文件路径 
print os.path.dirname(file_path)

Output:
/Users/demon.li
#分离文件名与扩展名 
print os.path.splitext(file_path)

Output:
('/Users/demon.li/log', '.txt')

查询函数

#判断文件/目录是否存在
print os.path.exists(file_path)

Output:
存在:True
不存在:False
#判断是否为绝对路径
print os.path.isabs(file_path)

Output:
True/False
#判断是否为文件且存在
print os.path.isfile(file_path)

Output:
True/False
#判断是否为目录且存在
print os.path.isdir(file_path)

Output:
True/False
#指定路径是否存在且为一个符号链接 
print os.path.islink(file_path)

Output:
True/False
#输出当前工作目录路径
print os.getcwd()

目录操作

dir_path=/Users/demon.li

#输出目录下的所有文件和目录列表
print os.listdir(dir_path)

#创建目录
print os.mkdir(dir_path)

#循环创建目录
print os.makedirs(dir_path)

Other

#与平台相关的路径分隔符
print os.sep
#执行操作系统相关的命令
#注意区分Windows和类Unix命令是不同的
command="cp ~/log.txt ~/log_new.txt"
os.system(command)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容