python 扫描文件夹下所有文件, 并进行多种格式间格式转化

目录

python 扫描文件夹下所有文件

python 扫描文件夹下所有文件,并进行格式转换


python 扫描文件夹下所有文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/3/2 17:30
# @Author  : ystraw
# @Site    : 
# @File    : test.py
# @Software: PyCharm Community Edition
# @function: 扫描文件夹下所有文件

import os

def scanDir(filePath):
    # 获取该路径下的所有文件
    files = os.listdir(filePath)

    # 遍历所有文件
    for file in files:
        # 把文件路径和文件名结合起来
        file_d = os.path.join(filePath, file)
        # 判断该文件是单个文件还是文件夹
        if os.path.isdir(file_d):  # 如果是文件夹则递归调用 scanDir() 函数
            scanDir(file_d)
        else:
            print("scan file: "+file_d)

if __name__ == '__main__':
    path = r'E:\software\python\py3.6\Lib\site-packages\bs4'
    scanDir(path)

python 扫描文件夹下所有文件,并进行格式转换

import os

def scanDir(filePath, codingType):
    # 获取该路径下的所有文件
    files = os.listdir(filePath)
    # 遍历所有文件
    for file in files:
        # 把文件路径和文件名结合起来
        file_d = os.path.join(filePath, file)
        # 判断该文件是单个文件还是文件夹
        if os.path.isdir(file_d):  # 如果是文件夹则递归调用 scanDir() 函数
            scanDir(file_d, codingType)
        else:
            # print("scan file:"+file_d)
            # 是文件,则进行转化格式
            codeTranslate(file_d, codingType)

# 返回字符的编码类型:判断文本编码类型
def getGncoding(data: bytes):
    # 枚举几种常见的编码类型:可以多加点
    CODES = ['GBK', 'UTF-8', 'ASCII', 'GB18030', 'BIG5', 'UTF-16', 'ISO-88591', 'GB23112']
    # 遍历编码类型:逐个尝试
    for code in CODES:
        try:
            # 尝试编码类型
            data.decode(encoding=code)
            if 'UTF-8' == code and data.startswith(b'\xef\xbb\xbf'):
                return 'UTF-8-SIG'
            return code
        except UnicodeDecodeError:
            continue
    return 'unknown'

def codeTranslate(file, codingType):
    # 判断要装换的文件类型
    if not file.endswith('.java'):
        return
    with open(file, 'rb+') as f:
        content = f.read()
        # 获取现在的编码格式
        nowConding = getGncoding(content)
        if nowConding.upper() == codingType.upper():
            print('已经是 ' + codingType + '编码格式,不需要转化')
        else:
            print("start translate file: "+file)
            print(nowConding + ' -->>> ' + codingType)
            # 更改编码方式
            content = content.decode(nowConding, errors="ignore").encode(codingType)
            f.seek(0)
            f.write(content)

if __name__ == '__main__':
    # 输出需要转化的路径和需要转化成的目标编码
    scanDir("D:\workspace-train\workspace-train\GuessNum\src\com\ys", 'utf-8')
    # codeTranslate(".\\test.java", 'utf-8')

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ystraw_ah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值