Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
连续读取文件并在列表中添加新行(python)_Python_List_File Io - Fatal编程技术网

连续读取文件并在列表中添加新行(python)

连续读取文件并在列表中添加新行(python),python,list,file-io,Python,List,File Io,我正在练习用python读取文件。我得到了一个文本文件,我想运行一个程序,不断读取这个文本文件,并将新写的行添加到列表中。要退出程序并打印出结果列表,用户应按“回车” 到目前为止,我编写的代码如下所示: import sys, select, os data = [] i = 0 while True: os.system('cls' if os.name == 'nt' else 'clear') with open('test.txt', 'r') as f:

我正在练习用python读取文件。我得到了一个文本文件,我想运行一个程序,不断读取这个文本文件,并将新写的行添加到列表中。要退出程序并打印出结果列表,用户应按“回车”

到目前为止,我编写的代码如下所示:

import sys, select, os

data = []
i = 0

while True:

    os.system('cls' if os.name == 'nt' else 'clear')
    with open('test.txt', 'r') as f:
        for line in f:
            data.append(int(line))
            
    print(data)
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        line_ = input()
        break
因此,要打破while循环,应按下“回车”键。为了公平起见,我只是从这里复制粘贴了解决方案:

但这段代码只是一次又一次地将所有行追加到我的列表中。 因此,假设我的文本文件包含以下行:

1
2
3
所以我的列表看起来像
data=[1,2,3,1,2,3,1,2,3…]
,在我按enter键之前有一定的长度。当我添加一行(例如
4
)时,它将变成
data=[1,2,3,1,2,3,1,2,2,3,4,1,2,3,4…]

因此,我在
append
命令之前寻找某种
if语句
,以便只追加新编写的行。但我想不出什么容易的事

我已经得到了一些提示,例如

  • 持续检查文件大小,仅读取新旧尺寸之间的零件
  • 跟踪行号并跳到下一次迭代中未追加的行
  • 目前,我想不出一个方法来做这件事。我试着摆弄
    enumerate(f)
    itertools.islice
    ,但无法使其工作。非常感谢您的帮助,因为我还没有采用程序员的思维方式。

    存储迭代之间的数据。这样可以在再次打开时高效地执行以下操作:

    data = []
    file_position = 0
    
    while True:
        with open('test.txt', 'r') as f:
            f.seek(file_position)  # fast forward beyond content read previously
            for line in f:
                data.append(int(line))
            file_position = f.tell()  # store position at which to resume
    

    我可以让它在Windows上工作。首先,退出
    ,同时退出
    -循环和继续读取文件是两个不同的问题。我假设退出
    while
    循环不是主要问题,并且由于您的
    select.select()
    语句在Windows上不能以这种方式工作,因此我使用在Ctrl-c上触发的
    try except
    子句创建了一个退出。(这只是一种方法)

    问题的第二部分是如何持续阅读文件。好吧,不要在
    while
    循环中一次又一次地重新打开它,而是在
    while
    循环之前打开它

    然后,一旦文件被更改,就会读取有效行或无效行。我想这是因为在
    f
    上的迭代有时可能会在文件完全编写之前发生(我不太确定)。无论如何,检查读取行很容易。我再次使用了
    try except
    子句,如果
    int(line)
    引发错误,它将捕获错误

    代码:

    import sys, select, os
    
    data = []
    
    with open('text.txt', 'r') as f:
        try:
            while True:
    
                os.system('cls' if os.name == 'nt' else 'clear')
                for line in f:
                    try:
                        data.append(int(line))
                    except:
                        pass
                    
                print(data)
        except KeyboardInterrupt:
            print('Quit loop')
    print(data)
    

    谢谢,那正是我想要的!几天来一直在寻找一种方法来实现这一点,最终它比预期的要简单。我将研究
    seek()
    tell()
    方法!也许你可以帮我解决另一个问题:是否有可能同时使用另一个文件执行该过程?因此,如果使用一个文件
    test2.txt
    ,这些行就会被添加到列表
    data2
    。谢谢,但这在我的mac上不起作用。我想知道如何在while循环之前打开文件,因为当一个新行被写入文件,而该文件已经被脚本打开时,它将无法识别新写入的行,还是我错了?同时退出while循环对我也不起作用。