【问题标题】:Is there a way to write multiple classes into a python file from text received from the user?有没有办法从用户收到的文本中将多个类写入 python 文件?
【发布时间】:2019-04-17 19:26:33
【问题描述】:

我正在尝试接收用户的输入(通过使用 wx.Choice),然后根据该数字,编辑 .py 文件以根据所选数字编辑每个类的内容

我有一个使用 wxpython 设置的 GUI,它有三个选项。带有数字 1-5、标题文本框和正文多行文本框的下拉菜单。在选择数字、输入标题和输入正文时,我可以成功地将类写入文件,但是如果我选择一个新数字,它只会用 GUI 中的新文本覆盖我已经写入文本文件的内容

这里是文本面板和框:

self.numberChoices = ['1', '2', '3', '4', '5']
qnNumber_label = wx.StaticText(panel, label="Quicknote Number:", pos=(20, 30))
self.number_Control = wx.Choice(panel, pos=(140, 30), size=(50, -1), choices=self.numberChoices)
widgets.append(qnNumber_label)
widgets.append(self.number_Control)

# Quicknote title text panel creation
qnTitle_label = wx.StaticText(panel, label='Quicknote Title:', pos=(20, 60))
self.title_Control = wx.TextCtrl(panel, pos=(140, 60))
widgets.append(qnTitle_label)
widgets.append(self.title_Control)

# Quicknote body text panel creation
qnBody_label = wx.StaticText(panel, label='Quicknote Text:', pos=(20, 90))
self.body_Control = wx.TextCtrl(panel, style=wx.TE_MULTILINE, pos=(140, 90), size=(300, 200))
widgets.append(qnBody_label)
widgets.append(self.body_Control)

当点击保存按钮时,它们会在此处被调用和写入:

quicknoteNumber = "class QN%s():" % self.number_Control.GetSelection()
quicknoteTitle = "\ttitle = '%s'" % self.title_Control.GetValue()
quicknoteBody = "\tnote = %s\n" % self.body_Control.GetValue().split("#")

ret = [quicknoteNumber, quicknoteTitle, quicknoteBody]
print ("\n".join(ret))
# print(ret)

file = open('config.py', 'w')

file.write("\n".join(ret))
file.close()

confirmation_text = 'Your quicknote was updated successfully!'
dlg = wx.MessageDialog(self, confirmation_text, 'Success', wx.OK)  # wx.OK|wx.ICON_INFORMATION
result = dlg.ShowModal()
dlg.Destroy()

以下是期望的结果:

class QN0():
    title = 'title'
    note = ['a line of notes\nanother line of notes\none last line of notes']

class QN1():
    title = 'title'
    note = ['a line of notes\nanother line of notes\none last line of notes']

但是,当我从下拉列表中选择一个新数字时,它只会替换我之前写入文件的内容。理想情况下,id 喜欢覆盖相同数量的类,因为这是一个用于快速笔记的编辑 GUI。 (例如,如果 QN0 类已经存在,当我从下拉列表中选择 QN0 时,它将编辑 QN0 类而不是再次重写它)。

【问题讨论】:

  • 打开文件时使用模式“a”(追加)而不是“w”(写入)。
  • furas,如果类已经存在,有没有办法覆盖? 'a' 有效,但现在我在 config.py 文件中获得了多个相同的类
  • 是的,你可以用“w”打开删除旧内容。现在你必须知道什么时候用“w”打开,什么时候用“a”打开。
  • 但我会以不同的方式做到这一点。一开始我会从文件中读取所有内容,以便我可以在内存中更改它(添加、删除、编辑),然后我会使用“w”再次写入所有内容
  • 我想最困难的部分是我只希望在编辑特定类时删除旧内容。我不希望删除任何类,除非我从下拉列表中选择其中一个类并且它已经存在于注释中。有没有办法运行一个循环来检查文件中的现有课程,然后在添加编辑的课堂笔记之前将其删除?

标签: python wxpython


【解决方案1】:

如 cmets 中所述,您必须使用选项“a+”(用于追加)而不是“w”打开文件。

例如:

f=open("config.py", "a+")

现在,你可以写任何你想要的,它会被添加到文件的末尾:

 f.write("Appended line!!!")

更多信息:

https://www.guru99.com/reading-and-writing-files-in-python.html#2

编辑:

阅读您的最后一条评论,尝试阅读整个内容,对其进行处理(例如使用正则表达式删除您想要的内容),然后再次将其写入整个内容。

问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2022-10-15
    • 2019-07-02
    • 2020-11-05
    • 2013-04-16
    相关资源
    最近更新 更多