简体   繁体   English

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

[英]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: 我正在编写一个脚本,它将打开一个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

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. 在上面的txt文件中,读取行/ 1310,然后执行一些操作以在云上发送该数据并将其标记为已发送。在下一次迭代中,从行/ 1321读取并再次发送,然后将其标记为已发送。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从txt文件的不同行中读取特定编号,并将其添加到txt中每个行块的末尾 - read specific number from different lines in a txt file and add it to the end of each line block in txt 从嵌套字典中的文件中读取最初未知数量的N行,然后在下一次迭代的N + 1行开始 - Read initially unknown number of N lines from file in a nested dictionary and start in next iteration at line N+1 需要 function 逐行读取大 txt 文件,如果没有更多行,打开文件并再次迭代 - Need function that read large txt file line by line and if no more lines, open file and iterate again Python“for line in file”,读取接下来的n行 - Python "for line in file", read the next n lines 在逐行读取文件的同时读取下一行和上一行 - Read next and previous lines while reading file line-by-line 读取csv行并将其另存为单独的txt文件,命名为行-python - Read csv lines and save it as seperate txt file, named as a line - python 使用唯一的分隔符和行尾将txt文件读取到pandas数据帧 - Read txt file to pandas dataframe with unique delimiter and end of line 如何读取txt文件中的每一行,该文件在python的rar文件中 - How to read each line in txt file which is in rar file in python 读取文件的下一行以确定是否打印当前行 - Read next lines of a file to determine whether or not to print current line 阅读 python 文件中的下 3 行 - Read the 3 next lines in python file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM