[英]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.