Python 保存一行后不断删除行

Python constantly deleting lines after saving one

我的代码看起来像

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 个,我们将不胜感激

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

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

这是对您的原始代码的一些重构:

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.