Python在保存后不断删除行

时间:2018-01-08 20:23:24

标签: python python-2.7 sorting line strip

我的代码看起来像

from __future__ import print_function
import linecache
from random import choice
from string import digits, ascii_lowercase
import random, string
import fileinput
 

 
L = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(10)])
print(L)
 
 
 
 

with open("input.txt") as f:
    for line in f:
        ok = (line)
        ok = line.strip()
        if line > 6:
            f = open('output.txt', 'a' )
            f.write( str(ok) +" " + str(L) + '\n')
            f.close()
            total_count = 0 
            for line in fileinput.input('output.txt', inplace=True):
                count = line.count(ok)
                if count > 0:
                    print(line, end='')
                    total_count += count
            print (total_count)

我的输入文件是:

55
99
42
65
49
49

我的问题是,它应该保存所有数字,但它只保存最后2,任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

似乎fileinput模块可能导致正确编写文件输出的问题,但我不确定该模块是如何工作的,因此我无法建议如何使用它。

主要更正可能是使用不同的文件处理程序指针来读取输入文件并写入输出文件(重用f,如评论中所述)。< / p>

以下是对原始代码的一些重构:

from __future__ import print_function
import linecache
from random import choice
from string import digits, ascii_lowercase
import random, string
from collections import defaultdict

L = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(10)])
print(L)

total_count = defaultdict(lambda: 0)

with open("input.txt", 'r') as f:
    for line in f:
        ok = line.strip()
        if int(line) > 6:
            total_count[int(line)] += 1
            with open('output.txt', 'a' ) as ff:
                ff.write( str(ok) + " " + str(L) + '\n')

infile_contents = []
outfile_contents = []

# get list of input.txt contents
with open('input.txt', 'r') as infile:
    for line in infile.readlines():
        infile_contents.append(line.strip())

# get list of output.txt first column contents
with open('output.txt', 'r') as outfile:
    for line in outfile.readlines():
        outfile_contents.append(line.split()[0])        

# dictionary to hold count of occurrences
totals = {}

# count occurrences
for num in infile_contents:
    totals[num] = outfile_contents.count(num)

# print counts
for item in totals.items():
    print('{num} appears {count} times.'.format(num=item[0], count=item[1]))

运行脚本两次后的示例输出:

vlVHVi3t9L
55 appears 2 times.
99 appears 2 times.
42 appears 2 times.
65 appears 2 times.
49 appears 4 times.