[英]read specific number from different lines in a txt file and add it to the end of each line block in txt
[英]Open a txt file, read a line, tag it at the end as 'Sent'. In next iteration, read lines which are untagged
我正在編寫一個腳本,它將打開一個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讀取並再次發送,然后將其標記為已發送。
我應該怎么做?
謝謝!
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.