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

时间:2016-01-25 18:39:43

标签: python python-2.7

我正在编写一个脚本,它将打开一个包含以下内容的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文件读取行/ 1310然后做一些操作以在云上发送该数据并将其标记为已发送..在下一次迭代中从行/ 1321读取并再次发送它然后将其标记为在结束时发送。

我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:1)

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')

答案 1 :(得分:1)

你可以这样做:

    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)