打开一个txt文件,读一行,最后标记为“Sent”。在下一次迭代中,读取未标记的行

2024-09-27 21:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个脚本,它将打开一个txt文件,内容如下:

/1320  12-22-16   data0/impr789.dcm     sent
/1340  12-22-18   data1/ir6789.dcm      sent
/1310  12-22-16   data0/impr789.dcm
/1321  12-22-16   data0/impr789.dcm

我只想读取未标记的行,例如在上面的txt文件read line/1310中,然后执行一些操作将数据发送到云上,并将其标记为已发送。。在下一次迭代中,从/1321行读取并再次发送它,然后在末尾将它标记为sent。你知道吗

我该怎么做?你知道吗

谢谢!你知道吗


Tags: 文件数据标记txt脚本内容readline
2条回答
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    for line in infile:
        end = line.strip().rsplit(None, 1)[-1]
        if end == "sent":
            outfile.write(line)
            continue
        doCloudStuff(line)
        outfile.write(line.rstrip() + '\tsent\n')

你可以这样做:

    lines=[]
    with open('path_to_file', 'r+') as source:
        for line in source:
            line = line.replace('\n','').strip()
            if line.split()[-1] != 'sent':
                # do some operation on line without 'sent' tag 
                do_operation(line)
                # tag the line
                line += '\tsent'
            line += '\n'
            # temporary save lines in a list
            lines.append(line)
        # move position to start of the file
        source.seek(0)
        # write back lines to the file
        source.writelines(lines)

相关问题 更多 >

    热门问题