背景
工作线上报错了,找运维下载了线上的日志文件排查问题,但是日志文件太大了,没办法用NotePad++打开,于是乎想着要切割一下日志文件
方法一:指定目标文件数量分割
import os
sourceFileName = 'normal-app.log'
fileNum = 10
def cutFile():
print("正在读取文件...")
sourceFileData = open(sourceFileName, 'r', encoding='utf-8')
ListOfLine = sourceFileData.read().splitlines()
totalLine = len(ListOfLine)
print("文件共有" + str(totalLine) + "行")
print("请输入需要将文件分割的个数:")
p = totalLine//fileNum + 1
print("需要将文件分成"+str(fileNum)+"个子文件")
print("每个文件最多有"+str(p)+"行")
print("开始进行分割···")
for i in range(fileNum):
destFileName = os.path.splitext(sourceFileName)[
0] + "_" + str(i + 1)+".log"
print("正在生成子文件" + destFileName)
destFileData = open(destFileName, "w", encoding='utf-8')
if(i == fileNum-1):
for line in ListOfLine[i*p:]:
destFileData.write(line+'\n')
else:
for line in ListOfLine[i*p:(i+1)*p]:
destFileData.write(line+'\n')
destFileData.close()
print("分割完成")
if __name__ == '__main__':
cutFile()
方法二:指定文件大小分割
这种方法是按照大小分割文件,会存在同一行被分割在两个文件中的情况
import os
filename = "normal-app.log"
size = 10000000
def createSubFile(srcName, sub, buf):
[des_filename, extname] = os.path.splitext(srcName)
filename = des_filename + '_' + str(sub) + extname
print('正在生成子文件: %s' % filename)
with open(filename, 'wb') as fout:
fout.write(buf)
return sub+1
def cutFile(filename, size):
with open(filename, 'rb') as fin:
buf = fin.read(size)
sub = 1
while len(buf) > 0:
sub = createSubFile(filename, sub, buf)
buf = fin.read(size)
print("ok")
if __name__ == "__main__":
cutFile(filename, size)
方法三:指定目标行数分割
import os
sourceFileName = 'normal-app.log'
lineNum = 100000
def cutFile():
print("正在读取文件...")
sourceFileData = open(sourceFileName, 'r', encoding='utf-8')
ListOfLine = sourceFileData.read().splitlines()
totalLine = len(ListOfLine)
print("文件共有" + str(totalLine) + "行")
print("请输入需要将文件分割的个数:")
fileNum = totalLine//lineNum + 1
print("需要将文件分成"+str(fileNum)+"个子文件")
print("开始进行分割···")
for i in range(fileNum):
destFileName = os.path.splitext(sourceFileName)[
0] + "_" + str(i + 1)+".log"
print("正在生成子文件" + destFileName)
destFileData = open(destFileName, "w", encoding='utf-8')
if(i == fileNum-1):
for line in ListOfLine[i*lineNum:]:
destFileData.write(line+'\n')
else:
for line in ListOfLine[i*lineNum:(i+1)*lineNum]:
destFileData.write(line+'\n')
destFileData.close()
print("分割完成")
if __name__ == '__main__':
cutFile()
|