Read/Write data from a Tabulated file format

huangapple go评论55阅读模式
英文:

Read/Write data from a Tabulated file format

问题

在我的Python程序中,我习惯将参数/变量值(主要是配置类型的值,如宽度/高度/速度等)存储在一个文本文件中,然后读取并使用它们。但这不够美观,我更希望使用可以制表的文件格式。那么,我有哪些选项可用?

以下是当前做法的示例:

Read/Write data from a Tabulated file format

这是我期望的效果:

Read/Write data from a Tabulated file format

英文:

So far in my python programs i use to store parameter/variable values(mostly configuration type values like width/heights/speed etc) in a text file,read them and use them.
But that is not aesthetically pleasing and i would prefer a file format that can be Tabulated. So what are my options available

Here is an example of current practice

Read/Write data from a Tabulated file format

And Here is what i am expecting.

Read/Write data from a Tabulated file format

答案1

得分: 1

以下是您要翻译的部分:

来自官方文档的File Formats部分详细介绍了Python标准库支持的所有文件格式。

然而,要处理配置文件,新的tomllib模块可能是您需要的。

例如,您的 config.toml 文件可能如下所示:

QR_pixel_density = 5
QR_border_size = 2

要解析 .toml 文件,只需执行以下操作:

import tomllib
with open('config.toml', 'rb') as f:
    data = tomllib.load(f)

    print(data)
    # {'QR_pixel_density': 5, 'QR_border_size': 2}

之后,只需遍历字典,将值添加到您正在使用的 GUI 库中。

话虽如此,由于tomllib模块是在版本3.11中新增的,所以对于Python 3.10或更早版本,configparser模块是另一个选项。

英文:

The File Formats section from the official documentation details all file formats supported within the Python Standard Library.

For working with configuration files however, the new tomllib module is probably what you're after.

For example, your config.toml file might look something like this:

QR_pixel_density = 5
QR_border_size = 2

And to parse the .toml file you would just do:

import tomllib
with open('config.toml', 'rb') as f:
    data = tomllib.load(f)

    print(data)
    # {'QR_pixel_density': 5, 'QR_border_size': 2}

After that just iterate over the dictionary to add the values into the GUI library you're using.

That being said, as the tomllib module is new in version 3.11, the configparser module is another option for Python 3.10 or earlier.

huangapple
  • 本文由 发表于 2023年4月10日 23:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定