将文件除以文件PYTHON的第一列

时间:2014-11-14 12:04:45

标签: python file

我有以下类型的file.txt

65000 data1 data2 data3
65000 data1 data2 data3
.
.
.
65000 data1 data2 data3
65001 data1 data2 data3
.
.
.
65001 data1 data2 data3

第一列的行数(第一个数字相同)对于每个参数都不同,所以我不能使用简单参数n = 25。

enter code here`lines_per_file = 69
 shortfile = None
 with open('longfile.txt') as longfile:
    for lineno, line in enumerate(longfile):
        if lineno % lines_per_file == 0:
            if shortfile:
                shortfile.close()
                short_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
            shortfile = open(short_filename, "w")
        shortfile.write(line)
    if shortfile:
        shortfile.close()

如何在许多较小的文件上分割文件

1 个答案:

答案 0 :(得分:0)

这样做

lines = 0
shortfile = None
with open('longfile.txt') as longfile:
   for lineno, line in enumerate(longfile):
       new_lines = line.split(' ')[0]
       if lines != new_lines:
           lines = new_lines
           if shortfile:
               shortfile.close()
               short_filename = 'small_file_{}.txt'.format(lines)
           shortfile = open(short_filename, "w")
       shortfile.write(line)
   if shortfile:
       shortfile.close()

这会导致在前面出现新号码时创建新的行文件