繁体   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