gpt4 book ai didi

python - 在python中将类对象读/写到dat文件

转载 作者:行者123 更新时间:2023-11-30 16:05:45 27 4
gpt4 key购买 nike

我有一个类对象,我想将其写入dat文件。需要将对象p1和p2写入dat文件。再次可以直接读入对象。我知道有一个相同的泡菜方法,但我不想要那样。

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)
p2 = Person("Michael", 30)
# Now I want to write this object into a dat file
fp = open("file.dat", "w")
fp.write(p1)

# And while reading I want this object to be read directly into the variable
fp = open("file.dat", "w")
p1 = fp.read()
p2 = fp.read()


python中有什么办法可以做到这一点吗?

这是对应的C程序要做的相同

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct car {
int id;
char name[15];
int price;
char colors[3][5];
} car;

int main()
{
car obj1 = { .id = 5,
.name = "honda city zx",
.colors = {"red", "black", "blue"}
};
car obj2 = { .id = 6,
.name = "honda city",
.colors = {"lal", "kala", "neela"}
};

FILE *fp;

//WRITING TO THE FILE
fp = fopen("car_details.dat", "w");
fwrite(&obj1, sizeof(obj1), 1, fp);
fwrite(&obj2, sizeof(obj2), 1, fp);
fclose(fp);

// READING FROM THE FILE
fp = fopen("car_details.dat", "r");
car obj;
while(fread(&obj, sizeof(obj), 1, fp))
{
printf("id : %d\nname : %s\nprice : %d\ncolors : {%s, %s, %s}\n\n", obj.id, obj.name, obj.price, obj.colors[0], obj.colors[1], obj.colors[2]);
}

return 0;
}


我如何在python中做同样的事情?

最佳答案

如果您确实想遵循相同的方法,可以尝试一下。但是我不建议这样做。

import pickle

class Car(object):
def __init__(self, id, name, price, color):
self.id = id
self.name = name
self.price = price
self.color = color

with open('car_details.dat', 'wb') as output:

obj1 = Car(5, "honda city zx", 1000, "Red")
pickle.dump(obj1, output, pickle.HIGHEST_PROTOCOL)

obj2 = Car(6, "Innova", 2000, "Grey")
pickle.dump(obj2, output, pickle.HIGHEST_PROTOCOL)

del obj1
del obj2

with open('car_details.dat', 'rb') as input:
obj1 = pickle.load(input)
print(obj1.id, obj1.name, obj1.price, obj1.color)
obj2 = pickle.load(input)
print(obj2.id, obj2.name, obj2.price, obj2.color)

关于python - 在python中将类对象读/写到dat文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60204341/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com