您的位置:首页 > 编程语言 > Python开发

python文件、文件夹操作

2018-03-27 21:53 309 查看
文件相关创建操作见:http://www.runoob.com/python/python-files-io.html
文件夹操作使用os
判断文件是否存在import os
import shutil
os.remove(path) #删除文件
os.removedirs(path) #删除空文件夹
os.mkdir(path) #创建文件夹
os.makedirs(path)#级联创建文件夹
shutil.rmtree(path) #递归删除文件夹

#先定义一个带路径的文件filename = "/home/mydir/test.txt"
#将文件路径分割出来file_dir = os.path.split(filename )[0]#判断文件路径是否存在,如果不存在,则创建,此处是创建多级目录
    if not os.path.isdir(file_dir):
        os.makedirs(file_dir)#然后再判断文件是否存在,如果不存在,则创建
    if not os.path.exists(filename ):
        os.system(r'touch %s' % filename)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 文件 文件夹