简体   繁体   中英

Open a txt file, read a line, tag it at the end as 'Sent'. In next iteration, read lines which are untagged

I am writing a script which will open a txt file with contents as follows:

/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

I want to read lines only which are not tagged eg. in above txt file read line /1310 and then do some operation to send that data on cloud and tagg it as sent.. In the next iteration read from line /1321 and send it again and then tag it as sent at the end.

How should i do this?

Thanks!

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

You can do it this way:

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM