目录
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')