Python实现TXT文件按固定大小分割与压缩重组

南乔
南乔
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍使用Python将单个TXT文本文件按固定字节数分割为多个小文件,并通过特定二进制标记进行重组的方法。代码重点处理了Unicode编码下的中文字符截断问题,利用struct模块打包字符以维持文件完整性,适用于大文本文件的分片处理场景。

Python文件分割与重组代码实现

直接展示核心实现代码。


'''
 
为了避免截断中文字符 
文件要求是 unicode 编码 
txt文件另存为对话框下面有下拉框,可选存 
储编码格式 
 
'''
 
import os 
import struct 
#导入所需python模块方法
 
filename = str(raw_input("Please enter an old file name: ")) 
filenamepre = str(raw_input("Please enter an new file name prefix: ")) 
count = 0
filecount = 0
maxcount = 20
newfilename = repr(filecount) + '.txt'
oldfile = open(filename,'rb') 
 
#www.iplaypy.com
bFirst = True
 
while True: 
  s = oldfile.read(512*8 - 4) 
if not s: 
  exit() 
 
filecount = filecount + 1
newfilename = filenamepre + repr(filecount).zfill(2) + '.txt'
newfile = open(newfilename,'wb') 
 
if not bFirst: 
  be = 0XFEFF
  newfile.write(struct.pack('H',be)) 
  newfile.write(s) 
 
be = 0X000A000D
newfile.write(struct.pack('I',be)) 
newfile.close() 
bFirst = False
oldfile.close() 
 
#文件相关操作切记要关闭

代码说明与参考建议

上述Python脚本演示了如何读取并分割压缩TXT文本文件,供读者参考实践,欢迎进一步测试与反馈。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表