【问题标题】:How to replace a line in a text file with the latest value in python?如何用python中的最新值替换文本文件中的一行?
【发布时间】:2020-03-25 21:28:37
【问题描述】:

我正在尝试为文件夹中的每个图像分配一个值,该值可以是 1 到 6 之间的任何值。图像显示在 GUI 中,然后从那里选择并写入值(单选按钮 1 到 6)到一个文本文件。

所以,如果我在一个文件夹中有 image1、image2 和 image3,并且我将值 4、5 和 6 分别分配给 image1、image2 和 image3,那么我的输出文件具有以下内容:

image1 4
image2 5
image3 6

这与我给出的代码完美配合。但我还在 GUI 中添加了两个按钮(下一个和上一个),以便用户可以通过单击这些按钮来更改他们的决定。

我想在退出 GUI 之前记录用户为每个图像选择的最后一个值。也就是说,如果用户分别为 image1、image2 和 image3 选择值 4、5 和 6,然后稍后将值 2 重新分配给 image1,则预期输出为:

image1 2
image2 5
image3 6

使用我的代码,它记录所有值而不检查它是否已经存在。即我得到的输出是:

image1 4
image2 5
image3 6
image1 2

我的代码如下:

def storeoutput(self):
        x= str(self.path)+ " " + str(str(int(self.v.get())) + "\n"
        output = open("output.txt", 'a')
        output.write(x)
        output.close()

【问题讨论】:

  • 要正确更新文件,您需要每次使用更新的值重写其所有内容。
  • @martineau 你能解释一下如何在代码中做到这一点吗?我是 python 新手...
  • 如果您在问题中添加足够的代码以使其成为问题的minimal reproducible example,我将很高兴。
  • 究竟有什么不清楚的地方?您在输出中多了一行,这正是“追加”所做的。
  • @Thomas:在输出中再写一行不会更新之前的行……

标签: python


【解决方案1】:

问题:替换文本文件中的一行

参考


注意:在 Python 3.7 之前,dict 默认不保留顺序!

  1. 文件数据

    CSV = """image1 4
    image2 5
    image3 6
    """
    
  2. 读取dict中的文件内容

    import csv, io
    
    # with open('file.csv') as f:
    with io.StringIO(CSV) as f:
        mydict = dict(csv.reader(f, delimiter=' '))
    
    print(mydict)
    >>>{'image1': '4', 'image2': '5', 'image3': '6'}
    
  3. 更新值

    mydict['image1'] = '2'
    
  4. dict

    # with open('file.csv', 'w') as f:
    with io.StringIO() as f:
        csv.writer(f, delimiter=' ').writerows(((k, v) for k, v in mydict.items()))
    

    文件内容

    print(f.getvalue())
    
    image1 2
    image2 5
    image3 6
    

【讨论】:

  • dicts 自 Python 3.7 以来一直保持顺序(自 3.6 以来在 cPython 中)。
【解决方案2】:

如果您将其作为字典而不是文本文件处理,该方法会更好。以下是一些步骤:

  1. 在问卷开始时创建一个初始字典。 (我假设这是一份问卷)

question_dict = {}

  1. 因此,您可以控制 image_name 和选项 (1-6)。您可以将每个问题与图像和选项一起存储在字典中,如下所示:
    question_dict["image_name1"] = 4 question_dict["image_name2"] = 5

  2. 如果从 UI 中单击上一个,您将从文件中获取已初始化的字典并重写已存在的 image_name 的值
    question_dict
    question_dict["image_name1"] = 2

  3. 最后,您可以将每个用户的整个字典保存到一个易于解析的 json 中,或者迭代字典并保存为任何其他格式。

理解代码片段:

#Create a file with an user_id_timestamp for the question session.
#Initial set of questions in the dictionary
dictionary = {}
# 1: Q1 and option selected and next is pressed, save the record into dictionary
# and save dictionary to a  file.
dictionary["image1"] = 4
# Repeat - 1, but this time with load the existing dictionary and write the new key-val and save
dictionary["image2"] = 5
# Repeat
dictionary["image3"] = 6

#Previous is clicked hence true
prev_clicked = True
if prev_clicked:
    # Assuming user is at image4 and clicks previous
    # 1. Open the saved dictionary as a file.
    # Save the new option to the already existing key to the dictionary as below
    dictionary["image3"] = 4
    # Save the dictionary again, as Repeat  

【讨论】:

    猜你喜欢
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2022-11-23
    • 2023-03-25
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    相关资源
    最近更新 更多