簡體   English   中英

如何在 Python 中 X 次后替換文件中的字符串?

[英]How to replace a string in a file after a X number of time in Python?

前提說明:

我有這個 Python 腳本 Main.py,它收集距離和溫度並將它們發送到文本文件 Data.txt。 目前我有它,所以它每次都替換文本字符串

編輯:

目前它只打印一串文本並且代碼反復覆蓋這一行,我想要的是代碼在覆蓋最舊的行之前打印該字符串的 10 行,就像下面的例子一樣。

例子:

# Main.py

while True:
    f=open("data.txt","a+")
    a = str(scan())+"\n"
    f.write(a);
    log.log("Wrote to file")
    log.log(a)
    with open("data.txt","rt") as fin:
        with open("data.txt","wt")as fout:
            for line in fin:
                fout.write(line.replace("scan()", "scan()"))
    f.close()

實際輸出:

[26.07, 32.31, 93.73, False] #it constantly overwrites this line.

題:

如何使它在替換字符串之前打印出至少 10 行文本?

需要的輸出示例:

    #print out 10 strings of text
    [23.07, 32.31, 93.73, False] 
    [27.03, 36.34, 93.73, False] 
    [26.07, 34.36, 93.73, False] 
    [28.02, 32.21, 93.73, False] 
    [24.03, 22.31, 93.73, False] 
    [22.07, 28.31, 93.73, False] 
    [29.04, 32.21, 93.73, False] 
    [26.07, 32.31, 93.73, False] 
    [26.07, 32.31, 93.73, False] 
    [26.07, 32.31, 93.73, False]

#new string of text comes in [26.07, 32.31, 93.73, True]
expected output:
   [27.03, 36.34, 93.73, False] 
   [26.07, 34.36, 93.73, False] 
   [28.02, 32.21, 93.73, False] 
   [24.03, 22.31, 93.73, False] 
   [22.07, 28.31, 93.73, False] 
   [29.04, 32.21, 93.73, False] 
   [26.07, 32.31, 93.73, False] 
   [26.07, 32.31, 93.73, False] 
   [26.07, 32.31, 93.73, False] 
   [26.07, 32.31, 93.73, True]  # replaces the string one, adding this new data into the list.

您可能會考慮使用time.sleep()以便每秒左右只寫入文件。

import time
import numpy as np

def scan():
    # your scanner here. 
    return list(np.random.randint(1, 10, 4))

a_list = list()

while True:
    a = str(scan()) + "\n"
    a_list.insert(0, a)
    a_list = a_list[:10]

    with open("data.txt", "wt") as fout:
        fout.write(''.join(a_list))
        time.sleep(1)

嘗試這個:

while True:
    txt = open("data.txt", "r").read()
    txt = txt.split("\n")
    if len(txt) == 10:
        txt.pop(0)
        txt.append("what you want to write")
    else:
        txt.append("what you want to write")
    f = open("data.txt", "w")
    f.write("\n".join(txt))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM