Python 拆分文本文件
我有一个文件夹,里面有一组文本文档。我想将每个文档拆分为两个或三个文档,每个文档的大小应为45-70kb 我该怎么做?我试过:Python 拆分文本文件,python,text,split,Python,Text,Split,我有一个文件夹,里面有一组文本文档。我想将每个文档拆分为两个或三个文档,每个文档的大小应为45-70kb 我该怎么做?我试过: def split_file(filename, pattern, size): with open(filename, 'rb') as f: for index, line in enumerate(f, start=1): with open(pattern.format(index), 'wb') as out:
def split_file(filename, pattern, size):
with open(filename, 'rb') as f:
for index, line in enumerate(f, start=1):
with open(pattern.format(index), 'wb') as out:
n=0
for line in chain([line], f):
out.write(line)
n += len(line)
if n >= 450000 and n <=700000:
break
if __name__ == '__main__':
split_file('folderadress', 'part_{0:03d}.txt', 20000)
def split_文件(文件名、模式、大小):
将open(filename,'rb')作为f:
对于索引,枚举中的行(f,start=1):
将open(pattern.format(index),“wb”)作为输出:
n=0
对于链中的直线([line],f):
输出。写入(行)
n+=len(行)
如果n>=450000且n这将使用不同的方法处理您的问题。出于测试目的,我已将每个文件的最大大小设置为1000字节:
import glob
import os
dname = './gash' # directory name
unit_size = 1000 # maximum file size
for fname in glob.iglob("%s/*" % dname):
with open(fname, 'rb') as fo:
data = True
n = 1
while data:
# read returns "" (False) on EOF
data = fo.read(unit_size)
if data:
sub_fname = fname + str(n)
with open(sub_fname, 'wb') as out:
out.write(data)
n += 1
这可能会在文件之间分割一行,但您不会说明这是否是一个问题。在我看来,这是完全错误的”实际上是什么意思?错误?意外输出?我什么都没做,没有任何错误。我对它有怀疑,它在做我想做的吗?