Python处理文件及文件夹

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 20 17:12:45 2020

@author: ZeroJ
"""

'''
    专治各种 目录&文件 读取问题
'''

import glob
import os

# 删除文件夹下的所有内容
def delFilesInDir(path):
    fileNames = glob.glob(path + r'\*')
    for fileName in fileNames:
        try:
            # 删除文件
            os.remove(fileName)
        except:
            try:
                # 删除空文件夹
                os.rmdir(fileName)
            except:
                # 文件夹内容不为空,不能删除
                delFilesInDir(fileName)
                # 现在文件夹内容为空,可以删除
                os.rmdir(fileName)

# 删除指定路径的 文件/文件夹(下面所有内容)
def delFileOrDir(path):
    if os.path.exists(path):
        if not os.path.isdir(path): # 文件
            os.remove(path)
        else:                       # 文件夹
            delFilesInDir(path)
            os.rmdir(path)
            

# 级联生成 文件夹[文件]
def generateFileWithDir(path):
    dirPath = ''
    if '.' in path:     # 文件
        dirPath = '\\'.join(path.split('\\')[:-1]) if '\\' in path else '/'.join(path.split('/')[:-1])
        if not os.path.exists(dirPath):     #如果需要生成的文件已有上级文件夹,则不生成文件夹
            os.makedirs(dirPath)
        with open(path, 'w', encoding='utf-8') as f:
            f.write('ok');
    else:               # 文件夹
        dirPath = path
        os.makedirs(dirPath)
        
            

# 获取文件夹下所有文件及对应的路径信息
def getAllFileInfo(dirPath):
    fileNames = glob.glob(dirPath + r'\*');
    for fn in fileNames:
        if not os.path.isdir(fn):
            allFileInfo.append(fn)
        else:
            getAllFileInfo(fn)

# 删除、生成 绝对定位/相对定位 下的文件
dstPath = 'E:/File_Note/Code/Python/CodeExe/dir/test.txt'    # 运行文件py在CodeExe下,可使用 '../dir/test.txt'
delFileOrDir(dstPath)
generateFileWithDir(dstPath)

# 获取 绝对定位/相对定位 下的所有文件信息
allFileInfo = []
srcPath = 'E:/File_Note/Code/Python/CodeExe'
getAllFileInfo(srcPath)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容