在文件中检查两次重复项-Python

发布于 2025-01-22 19:52:38 字数 1142 浏览 1 评论 0原文

config.yml示例,

DBtables:
  CurrentMinuteLoad:
    CSV_File: trend.csv
    Table_Name: currentminuteload

GUI图像, “

这可能不是最干净的途径。

我正在制作一个为我使用的另一个python脚本创建config.yml文件的GUI。

使用pysimplegui,我的按钮无法像我期望的那样运行。当前并准确检查参考名称(例如,此处是CurrentMinuteloAd),如果存在,它将踢回去,但会跳过表格的支票(因此Elif语句被跳过)。添加表仍然有效,我只是没有得到想要的双重检查。另外,我必须在GUI中两次点击“确定”按钮才能工作吗?一个怪异的怪癖,对我来说没有任何意义。

def add_table():
  window2.read()
  with open ("config.yml","r") as h:
    if values['new_ref']  in h.read():
      sg.popup('Reference name already exists')  
    elif values['new_db']  in h.read():
      sg.popup('Table name already exists')
    else:
      with open("config.yml", "a+") as f:
        f.write("\n  " + values['new_ref'] +":")
        f.write("\n    CSV_File:" + values['new_csv'])
        f.write("\n    Table_Name:" + values['new_db'])
        f.close()
        sg.popup('The reference "' + values['new_ref'] + '" has been included and will add the table "' + values['new_db'] + '" to PG Admin during the next scheduled upload')

config.yml example,

DBtables:
  CurrentMinuteLoad:
    CSV_File: trend.csv
    Table_Name: currentminuteload

GUI image,
GUI

This may not be the cleanest route to take.

I'm making a GUI that creates a config.yml file for another python script I'm working with.

Using pysimplegui, My button isn't functioning the way I'd expect it to. It currently and accurately checks for the Reference name (example here would be CurrentMinuteLoad) and will kick it back if it exists, but will skip the check for the table (so the ELIF statement gets skipped). Adding the table still works, I'm just not getting the double-check that I want. Also, I have to hit the Okay button twice in the GUI for it to work?? A weird quirk that doesn't quite make sense to me.

def add_table():
  window2.read()
  with open ("config.yml","r") as h:
    if values['new_ref']  in h.read():
      sg.popup('Reference name already exists')  
    elif values['new_db']  in h.read():
      sg.popup('Table name already exists')
    else:
      with open("config.yml", "a+") as f:
        f.write("\n  " + values['new_ref'] +":")
        f.write("\n    CSV_File:" + values['new_csv'])
        f.write("\n    Table_Name:" + values['new_db'])
        f.close()
        sg.popup('The reference "' + values['new_ref'] + '" has been included and will add the table "' + values['new_db'] + '" to PG Admin during the next scheduled upload')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

分分钟 2025-01-29 19:52:38

当您使用h.read()时,应该保存值,因为它会像流一样读取它,然后随后的调用此方法会导致一个空字符串。

尝试这样的编辑代码:

 with open ("config.yml","r") as h:
    content = h.read()
    if values['new_ref']  in content:
      sg.popup('Reference name already exists')  
    elif values['new_db']  in content:
      sg.popup('Table name already exists')
    else:
        # ...

When you use h.read(), you should save the value since it will read it like a stream, and subsequent calls for this method will result in an empty string.

Try editing the code like this:

 with open ("config.yml","r") as h:
    content = h.read()
    if values['new_ref']  in content:
      sg.popup('Reference name already exists')  
    elif values['new_db']  in content:
      sg.popup('Table name already exists')
    else:
        # ...
凉风有信 2025-01-29 19:52:38

您应该使用真正的YAML解析器更新YAML文件,这将允许您
要检查重复的值,而不在中使用,这会给您false
当新值是现有值(或键)的子字符串时,阳性。

在下面,我添加了两次值,并显示结果YAML。这
第一次围绕new_refnew_db找不到
匹配虽然是现有值的子字符串。第二次
使用相同的值,当然在先前添加的
值。

import sys
import ruamel.yaml
from pathlib import Path

def add_table(filename, values, verbose=False):
    error = False
    yaml = ruamel.yaml.YAML()
    data = yaml.load(filename)
    dbtables = data['DBtables']
    if values['new_ref'] in dbtables:
        print(f'Reference name "{values["new_ref"]}" already exists') # use sg.popup in your code
        error = True
    for k, v in dbtables.items():
        if values['new_db'] in v.values():
            print(f'Table name "{values["new_db"]}" already exists')
            error = True
    if error:
        return
    dbtables[values['new_ref']] = d = {}
    for x in ['new_cv', 'new_db']:
        d[x] = values[x]
    yaml.dump(data, filename)
    if verbose:
        sys.stdout.write(filename.read_text())
    

values = dict(new_ref='CurrentMinuteL', new_cv='trend_csv', new_db='currentminutel')
add_table(Path('config.yaml'), values, verbose=True)
print('========')
add_table(Path('config.yaml'), values, verbose=True)

给出:

DBtables:
  CurrentMinuteLoad:
    CSV_File: trend.csv
    Table_Name: currentminuteload
  CurrentMinuteL:
    new_cv: trend_csv
    new_db: currentminutel
========
Reference name "CurrentMinuteL" already exists
Table name "currentminutel" already exists

You should update the YAML file using a real YAML parser, that will allow you
to check on duplicate values, without using in, which will give you false
positives when a new value is a substring of an existing value (or key).

In the following I add values twice, and show the resulting YAML. The
first time around the check on new_ref and new_db does not find
a match although it is a substring of existing values. The second time
using the same values there is of course a match on the previously added
values.

import sys
import ruamel.yaml
from pathlib import Path

def add_table(filename, values, verbose=False):
    error = False
    yaml = ruamel.yaml.YAML()
    data = yaml.load(filename)
    dbtables = data['DBtables']
    if values['new_ref'] in dbtables:
        print(f'Reference name "{values["new_ref"]}" already exists') # use sg.popup in your code
        error = True
    for k, v in dbtables.items():
        if values['new_db'] in v.values():
            print(f'Table name "{values["new_db"]}" already exists')
            error = True
    if error:
        return
    dbtables[values['new_ref']] = d = {}
    for x in ['new_cv', 'new_db']:
        d[x] = values[x]
    yaml.dump(data, filename)
    if verbose:
        sys.stdout.write(filename.read_text())
    

values = dict(new_ref='CurrentMinuteL', new_cv='trend_csv', new_db='currentminutel')
add_table(Path('config.yaml'), values, verbose=True)
print('========')
add_table(Path('config.yaml'), values, verbose=True)

which gives:

DBtables:
  CurrentMinuteLoad:
    CSV_File: trend.csv
    Table_Name: currentminuteload
  CurrentMinuteL:
    new_cv: trend_csv
    new_db: currentminutel
========
Reference name "CurrentMinuteL" already exists
Table name "currentminutel" already exists
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文