【发布时间】:2020-02-13 09:25:28
【问题描述】:
我有一个类对象,我想将它写入 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 中做同样的事情?
【问题讨论】:
-
术语说明,
p1和p2不是“类对象”,它们是类Person的实例,Person是类对象。 -
有没有办法一次写入整个对象?
-
无论如何,Python 对象不是原始结构,因此您不能像使用 C 结构那样直接编写它。 究竟你想完成什么?为什么
pickle不适合? -
好的,简单的东西:用这种语言编码东西只是为了编码在另一种低级语言中工作方式完全相同的东西==无用,毫无意义,浪费时间。用任何语言编写“完成任务”的东西==很好。在这里和你的导师一起重新审视你的目标,当他们说“用 python 写这个”时,你很可能把它们当真了。他们可能希望的意思是编写在python中执行相同“目标”的等效代码。
-
文字墙之二:在python的时候,写python。不是c,不是java,不是xyz,你根据你使用的语言编写代码。用python写python。
标签: python c oop file-handling