[英]How to replace a line in a text file with the latest value in python?
I'm trying to assign a value to each image in a folder where the value can be anything from 1 to 6. The image is shown in a GUI and from there value (radio buttons 1 to 6) is chosen and written to a text file.我正在尝试为文件夹中的每个图像分配一个值,该值可以是 1 到 6 之间的任何值。图像显示在 GUI 中,从那里选择值(单选按钮 1 到 6)并将其写入文本文件。
So, if I have image1, image2, and image3 in a folder and if I'm assigning values 4, 5, and 6 respectively to image1, image2, and image3 then my output file has the following:因此,如果我在一个文件夹中有 image1、image2 和 image3,并且我分别为 image1、image2 和 image3 分配值 4、5 和 6,那么我的输出文件具有以下内容:
image1 4
image2 5
image3 6
this is working perfectly with my code given.这与我给出的代码完美配合。 But I also added two buttons (next and previous) to the GUI so that the user can change their decisions by clicking those buttons.但我还在 GUI 中添加了两个按钮(下一个和上一个),以便用户可以通过单击这些按钮来更改他们的决定。
I want to record the last value the user select for each image before exiting the GUI.我想在退出 GUI 之前记录用户为每个图像选择的最后一个值。 That is, if a user select values 4, 5, and 6 respectively to image1, image2, and image3 and then later reassigns image1 with value 2, the expected output is:也就是说,如果用户分别为 image1、image2 和 image3 选择值 4、5 和 6,然后将值 2 重新分配给 image1,则预期输出为:
image1 2
image2 5
image3 6
with my code, it is recording all values without checking if or if not it already exists.使用我的代码,它记录所有值而不检查它是否已经存在。 ie the output that I'm getting is:即我得到的输出是:
image1 4
image2 5
image3 6
image1 2
My code is given below:我的代码如下:
def storeoutput(self):
x= str(self.path)+ " " + str(str(int(self.v.get())) + "\n"
output = open("output.txt", 'a')
output.write(x)
output.close()
Question : Replace a line in a text file问题:替换文本文件中的一行
Reference参考
The csv module implements classes to read and write tabular data in CSV format. csv 模块实现了以 CSV 格式读取和写入表格数据的类。
An associative array, where arbitrary keys are mapped to values.一个关联数组,其中任意键映射到值。
Tutorial - 5.5. 教程 - 5.5。 Dictionaries 字典
Another useful data type built into Python is the dictionary Python 内置的另一种有用的数据类型是字典
Note : A dict
does not preserve the order by default, before Python 3.7!注意:在 Python 3.7 之前, dict
默认不保留顺序!
File data档案资料
CSV = """image1 4 image2 5 image3 6 """
Read the file contents in a dict
在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'}
Update the value更新值
mydict['image1'] = '2'
Write the dict
写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()))
File content :文件内容:
print(f.getvalue()) image1 2 image2 5 image3 6
The approach would better if you handle it as dictionary rather than text files.如果您将其作为字典而不是文本文件处理,这种方法会更好。 Some steps below:下面的一些步骤:
question_dict = {}
Since, you would have control over the image_name and the options (1-6).因为,您可以控制 image_name 和选项 (1-6)。 You can store each question with image and the option in the dictionary as below:您可以在字典中存储带有图像和选项的每个问题,如下所示:
question_dict["image_name1"] = 4 question_dict["image_name2"] = 5
if the previous is clicked from the UI, you would get the already initialized dictionary from a file and rewrite the value of the already existing image_name如果从 UI 单击前一个,您将从文件中获取已初始化的字典并重写已存在的 image_name 的值question_dict
question_dict["image_name1"] = 2
Finally, you can save the entire dictionary, per user into a json which would then be easy to parse, or iterate the dictionary and save to any other format.最后,您可以将每个用户的整个字典保存到一个 json 中,以便于解析,或者迭代字典并保存为任何其他格式。
Code Snippet for understanding:用于理解的代码片段:
#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.