如何计算行数并在文件中插入该值

时间:2015-11-09 01:49:28

标签: python python-2.7

我的输入文件为:

aa 12
bb 23 
cc 34
dd 45

依此类推......这只是文件的格式。我的实际文件有大约10,000行。我希望输出为:

\data\
 n-grams = 4

 \1-grams:
 aa 12
 bb 23
 cc 34
 dd 45

 \end\

我使用过这段代码:

 with open("Input.txt") as infile:

    with open("Output.txt","w") as outfile:
        for i,line in enumerate(infile):
            if i==0:
                # 1st line
                count = sum(1 for line in infile)                
                outfile.write("\data\ \n")
                outfile.write("n-grams = " + str(count) + '\n\n')
                outfile.write("\\1-grams:\n")
            elif i==3:
               # 4th line
               pass
            else:
              outfile.write(line)

但是,这段代码正在插入

\data\
n-grams = 3

\1-grams:

不打印其余数据。并且,它只计算3个元素行而不是4个。如何修改它以使其工作?

1 个答案:

答案 0 :(得分:1)

我会这样做:

with open('infile.txt', 'r') as f:
    lines = f.readlines()

with open('outfile.txt', 'w') as f:
    f.write('\\data\\\n')
    f.write('n-grams = {}\n'.format(len(lines)))
    f.write('\\1-grams:\n')
    for l in lines:
        f.write(l)