从文件中删除行,在循环读取 python 内

Remove line from file, inside a loop reading python

我在读取名为 ReadingFile 的文件时遇到一个奇怪的问题。所以我要做的是读取名为 ReadingFile 的文件中的所有内容,并在读取一行后立即删除在 ReadingFile.

中读取的那一行

代码:

import os
import logging

logger = logging.getLogger(__name__)  
logger.setLevel(logging.INFO)

file_handler = logging.FileHandler('Test.log')
file_formatter = logging.Formatter('[%(asctime)s]: %(message)s')
file_handler.setFormatter(file_formatter)

logger.addHandler(file_handler)

def RemoveOneLine(file, ToDelete):
    with open(file, 'r') as f:
        lines = f.readlines()

    with open(file, 'w') as f:
        for line in lines:
            if line.strip('\n') != ToDelete:
                f.write(line)

def Test(filename):
    with open(filename, 'r') as a_file:
        for line in a_file:
            test_line = line.strip()
            
            logger.info('was [{}]'.format(test_line))
            RemoveOneLine(filename, test_line)

Test('ReadingFile')

ReadingFile的内容,我会上传到Pastebin,因为它太大了。 https://pastebin.com/9kTwv5Kj 这个大名单是什么?这是一个帐户列表,别担心。它们是 public 密钥。知道密钥不会造成任何伤害。

问题。

一段时间后,我得到截断的数据和错误的数据,错误的 public 键.. public 键太长或太短,或者相同长度的键但在 ReadingFile 中不存在..

正如您在 pastebine 中看到的那样,第一行是 GA25ETO3HJFO4NJLM2PG25WGHWMX35DS4KI7BLY2PA5DTNCDUN2UUSVP 当循环到达第 GAL7MUG4G3MMO24JKESAMWWIAJT4L7TKX74EONZSB7RKDUGAYSWUQ7JG 行时它开始截断数据..

比较屏幕,左侧未更改,右侧截断..

我需要的只是:Read file -> Read Line -> Remove Line that was read -> Read again first line -> Close program when file is empty..也许我做了方法不对,我是 python.

的新手

怎么了?

试试这个。代码更正如下:

  1. 添加close()方法,每次完成文件处理。
  2. Test()函数[=27]中添加missedreadlines()方法 =].

[代码]

import os
import logging
logger = logging.getLogger(__name__)  
logger.setLevel(logging.INFO)
#You can clear log file eatch time using  mode='w' 
#OR you can use mode='a' to Append it
file_handler = logging.FileHandler('Test.log', mode='w') 
file_formatter = logging.Formatter('[%(asctime)s]: %(message)s')
file_handler.setFormatter(file_formatter)

logger.addHandler(file_handler)

def RemoveOneLine(file, ToDelete):
    with open(file, 'r') as f:
        lines = f.readlines()
        f.close() # we can now close the file after readlines()
    with open(file, 'w') as f:
        for line in lines:
            if line.strip('\n') != ToDelete:
                f.write(line)
        f.close() # we can close the file now after we have update it
        
def Test(filename):
    with open(filename, 'r') as a_file:
        lines_a_file = a_file.readlines() #should add readlines() here
        a_file.close() # we can now close the file after readlines()
        for line in lines_a_file:
            test_line = line.strip()
            logger.info('was [{}]'.format(test_line))
            RemoveOneLine(filename, test_line)

Test('ReadingFile')