代码之家  ›  专栏  ›  技术社区  ›  OPP

Python在保存行后不断删除行

  •  -1
  • OPP  · 技术社区  · 8 年前

    我的代码看起来像

    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 回复  |  直到 8 年前
        1
  •  0
  •   chickity china chinese chicken    8 年前

    似乎 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.