简体   繁体   English

在文本文件中存储Python实例属性的更好方法是什么?

[英]What is a better way to store Python instance attributes in a text file?

I need to store a relatively large list of changeable instance variables in a text file. 我需要在文本文件中存储相对较大的可变实例变量列表。 This is a breakdown of my current method for reading and writing: 这是我目前的读写方法的细分:

class Car():
    def __init__(self, name, size, color):
        self.name = name
        self.size = size
        self.color = color

aa = Car('truck','big','red')
bb = Car('sedan','small','blue')
cc = Car('bus','big','yellow')

with open('test.csv', 'ab') as ff:
    ww = csv.writer(ff)
    for i in [aa, bb, cc]:
        ww.writerow([i.name, i.size, i.color])

carList = []
with open('test.csv', 'rb') as ff:
    rr = csv.reader(ff)
    for i in rr:
        carList.append(Car(i[0], i[1], i[2]) )

print carList[1].color

This has a few problems. 这有一些问题。 The number and order of columns are effectively hardcoded in. I am not sure if this can be easily avoided, but I feel like it should be. 列的数量和顺序已有效地进行了硬编码。我不确定是否可以轻松避免这种情况,但我认为应该这样做。 Modifying an instance in the middle of the file would, I believe, require iterating through all lines and rewriting them while checking 'name's (which are unique unlike the other variables) for a line to write differently. 我认为,修改文件中间的实例将需要遍历所有行并重写它们,同时检查“名称”(与其他变量不同,它们是唯一的)以使行写的方式不同。 Also I can't directly access the values by name until after instantiating, which again is not really that big of a deal, but I feel like I should avoid it. 另外,在实例化之后,我无法直接通过名称访问值,这虽然没什么大不了的,但是我觉得应该避免使用它。

This system works well enough, but it seems like it could be greatly improved. 该系统运行良好,但似乎可以大大改进。

You might think about using a database management system, like postgresql, or mysql. 您可能会考虑使用数据库管理系统,例如postgresql或mysql。 (And maybe even a fancy new noSql db ?) They worked and generally solved the problem of how to handle large data and still keep performance up... (甚至可能是新的noSql db吗?)他们工作了,通常解决了如何处理大数据并仍保持性能的问题。

If you devise your own format, you might end up at a point where you reimplement things like indexes (eg a btree) to improve performance. 如果您设计自己的格式,则可能最终会重新实现索引(例如btree)之类的东西以提高性能。

That being said: For your simple example, I would say csv is suitable. 话虽如此:对于您的简单示例,我想说csv是合适的。 Just add a header line (name;size;color) so that one can see the order of the columns from the header. 只需添加标题行(名称;大小;颜色),即可从标题中看到列的顺序。 This solves the hardcoding the order problem... 这解决了硬编码订单问题...

I've never used it, but check out pickle/cpickle . 我从未使用过它,但请查看pickle / cpickle It might be easier to handle : 可能更容易处理:

# Save a dictionary into a pickle file.
import pickle

favorite_color = { "lion": "yellow", "kitty": "red" }

pickle.dump( favorite_color, open( "save.p", "wb" ) )


#Load the dictionary back from the pickle file.

favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 什么是从Python文件中读取内容的更好方法? - What is a better way to readlines from Python file? 在Python中针对一个项目存储属性列表的更好方法是什么? - What is a better way to store a list of properties against one item in Python? Python Spark Dataframes:将组导出到文本文件的更好方法 - Python Spark Dataframes: Better way to export groups to text file Python 3:有没有更好的方法来查找和替换文本文件中的某些项目? - Python 3: Is there a better way to find and replace certain items in a text file? 通过self .__ setattr__进行迭代生成的实例属性。 有没有更好的办法? - Instance attributes, generated from iterable with self.__setattr__. Is there a better way? 什么是在python中导入文本文件的快速方法? - what is a quick way to import a text file in python? 有没有更好的方法来解析python文件? - Is there a better way to parse a file in python? 在Python中引用实例属性的快捷方式 - Shorthand way to refer to instance attributes in Python 在python中存储和使用大型文本文件的最佳方法 - Best way to store and use a large text-file in python 什么是在python中存储字典和json文件类型的推荐方法 - What is recommended way to store dictionaries and json file type in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM