Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将文件数据存储为类对象?_Python_Python 3.x - Fatal编程技术网

Python 如何将文件数据存储为类对象?

Python 如何将文件数据存储为类对象?,python,python-3.x,Python,Python 3.x,假设我们有一门课: class Car: def __init__(self, model, name, price): self.model = model self.name = name self.price = price 和.txt文件: 201 BMW 1.2 202 Mercedes Benz 1.6 是否可以在车型中存储'201'和'202',在名称中存储'BMW'和'Merc

假设我们有一门课:

class Car:
    def __init__(self, model, name, price):
        self.model = model
        self.name = name
        self.price = price
和.txt文件:

201    BMW              1.2
202    Mercedes Benz    1.6
是否可以在
车型中存储'201'和'202',在
名称中存储'BMW'和'Mercedes-Benz',在
价格中存储'1.2和1.6',而无需手动执行此操作

    car1 = Car('201', 'BMW', 1.2)
    car2 = Car('202', 'Mercedes Benz', 1.6)
。。。这样,而是直接读取和存储数据作为类对象

我已尝试解析文件中的数据,如下所示:

    cars = []
    file = open('store-data.txt')
    content = file.readlines()
    for x in range(len(content)):
        new_car = Car()
        cars.append(new_car)

    for car in cars:
        print(car)
但会出现以下错误:

TypeError: __init__() missing 3 required positional arguments: 'model', 'name', and 'price'.

你试过这样的东西吗-

cars = []
file = open('store-data.txt')
content = file.readlines()
for c in content:
    model, name, price = c.strip().split()
    new_car = Car(model, name, price)
    cars.append(new_car)


for car in cars:
    print(car)

代码的问题在同一个错误消息中解释:
TypeError:init()缺少3个必需的位置参数:“model”、“name”和“price”

当您试图创建没有任何价值的汽车时:
new\u car=car()
。您缺少的步骤是解析文件中每一行的内容。为此,您必须按空格(您提供的示例中唯一的分隔符)对行进行分区:
line.split()
将执行您需要的操作,并且返回的列表中有三个元素:型号、制造商名称和价格。下一步是将价格转换为浮动(其他数据似乎是文本)

调用
strip()
也将删除所有可能的前缀和后缀空间

parts = line.strip().split()
car = Car(part[0], part[1], float(part[2]))
最后的代码,根据您自己的问题:

    cars = []
    file = open('store-data.txt')
    content = file.readlines()
    for x in range(len(content)):
        parts = content[x].strip().split()
        new_car = Car(parts[0], parts[1], float(parts[2]))
        cars.append(new_car)
一个重要的问题是,我们不是关闭文件,而是打开它。结构
with
将允许Python在文件工作完成后(当
with
块结束时)关闭该文件

另外,您不需要迭代文件中的行数,您可以直接运行它们。这是因为
for
迭代一个列表,实际上
range()
返回一个(整数)列表

现在,有几个问题需要改进:将字符串转换为浮点数(
float()
),可能引发ValueError异常。此外,我们正在计算所有行将具有预期的格式

    cars = []
    with open('store-data.txt') as file:
        for x in file.readlines():
            parts = x.strip().split()

            if len(parts) == 3:
                try:
                    new_car = Car(parts[0], parts[1], float(parts[2]))
                    cars.append(new_car)
                except ValueError:
                    print("Missing price in line: " + x)
            else:
                print("Formatting error in line: " + x)

最后,由于我们有一个制造商“Mercedes-Benz”,其名称中包含分隔符,因此我们必须考虑到字符串的各个部分与汽车的值之间可能不会有直接的对应关系。我们确信第一个值是模型(#0,
parts[0]
),最后一个值(#-1,
parts[-1]
,这是Python特有的)是价格。中间的值是制造商名称的不同部分

幸运的是,在Python中,我们可以从更大的列表中提取子列表(这称为切片)。只需列举第一个位置和最后一个位置,并用冒号分隔它们。请记住,最终位置从不包括在内。因此,制造商名称将包含在
部分[1:-1]
中。我们还可以使用
join(ch,l)
fromstr,该方法使用列表
l
的成员生成一个新字符串,并用字符
ch
分隔它们。即使在制造商名称仅扩展一个零件的情况下,这也会起作用

if len(parts) >= 3:
        model = parts[0]
        str_price = parts[-1]
        name = str.join(' ', parts[1:-1])
        
        try:
            new_car = Car(model, name, float(str_price))
因此,最后:

    cars = []
    with open('store-data.txt') as file:
        for x in file.readlines():
            parts = x.strip().split()

            if len(parts) >= 3:
                model = parts[0]
                str_price = parts[-1]
                name = str.join(' ', parts[1:-1])
        
                try:
                    new_car = Car(model, name, float(str_price))
                    cars.append(new_car)
                except ValueError:
                    print("Missing price in line: " + x)
            else:
                print("Formatting error in line: " + x)


您需要编写自己的解析代码,也许可以查看python中的pickling,并让我知道您的意思是否如我所记得的,您不能对类进行pickle/序列化。我过去所做的是对类初始化变量进行pickle/序列化。最简单的方法是在你的类上写一个方法,给你一个可以存储的格式化字符串。您是否尝试为任务编写代码?你遇到具体问题了吗?如果没有-你认为这个过程的逻辑步骤是什么?你需要帮助的是哪一部分?阅读YAML和pickle。梅赛德斯-奔驰
@Tomerikoo会有问题,现在已经解决了。
    cars = []
    with open('store-data.txt') as file:
        for x in file.readlines():
            parts = x.strip().split()

            if len(parts) >= 3:
                model = parts[0]
                str_price = parts[-1]
                name = str.join(' ', parts[1:-1])
        
                try:
                    new_car = Car(model, name, float(str_price))
                    cars.append(new_car)
                except ValueError:
                    print("Missing price in line: " + x)
            else:
                print("Formatting error in line: " + x)