【问题标题】:When writing twice to a CSV it works only in a particular order向 CSV 写入两次时,它仅按特定顺序工作
【发布时间】:2021-03-29 12:16:03
【问题描述】:

在下面的示例中,我从一个类中创建了两个对象,然后将传入的详细信息写入 CSV 文件。对象和 CSV 文件创建得很好,但取决于我何时进行写入 - 它会或不会工作。

问题出在区块中:

# Create > Write > Create > Write
dave = Character('PC', 'Dave', 'Warrior', 10, 2, 20)
dave.write_to_csv()
dan = Character('PC', 'Dan', 'Wizard', 5, 20, 5)
dan.write_to_csv()

在上述顺序中,'dan' 永远不会添加到 CSV。但是,如果我将其更改为以下内容,则两者都按需要编写:

# Create > Create > Write > Write
dave = Character('PC', 'Dave', 'Warrior', 10, 2, 20)
dan = Character('PC', 'Dan', 'Wizard', 5, 20, 5)
dave.write_to_csv()
dan.write_to_csv()

这里有什么问题?

完整代码:

import csv

class Character(object):
    def __init__(self, type, name, character_class, health, mana, strength):
        self.type = type
        self.name = name
        self.character_class = character_class
        self.health = health
        self.mana = mana
        self.strength = strength
        print('New character made')

        with open('character_file.csv', 'w') as character_file:
            character_writer = csv.writer(character_file)
            character_writer.writerow(['Type', 'Name', 'Class', 'Health', 'Mana', 'Strength'])

    def write_to_csv(self):
        with open('character_file.csv', 'a') as character_file:
            fields = [self.type, self.name, self.character_class, self.health, self.mana, self.strength]
            character_writer = csv.writer(character_file)
            character_writer.writerow(fields)
            print(f"{self.name} added to the Character Sheet.")
            # character_file.close() <-- shouldn't be needed as 'with' contains a finally > close?


# Create > Write > Create > Write
# Creating the Character then writing to the CSV works for Dave, but Dan is NOT written
dave = Character('PC', 'Dave', 'Warrior', 10, 2, 20)
dave.write_to_csv()
dan = Character('PC', 'Dan', 'Wizard', 5, 20, 5)
dan.write_to_csv()

# Create > Create > Write > Write
# Creating BOTH Characters then writing to the CSV works for BOTH
#dave = Character('PC', 'Dave', 'Warrior', 10, 2, 20)
#dan = Character('PC', 'Dan', 'Wizard', 5, 20, 5)
#dave.write_to_csv()
#dan.write_to_csv()

【问题讨论】:

  • 每次创建Character 实例时,文件都会被清除。不知道你打算如何工作。

标签: python csv


【解决方案1】:

每次调用Character的构造函数时,头部都会写入csv文件,文件的所有内容都会被丢弃。尝试只写一次标题。在another answer of mine 中有一个 write 函数,它只在尚未写入的情况下写入 header。

试试这样:

class Character(object):
    def __init__(self, type, name, character_class, health, mana, strength):
        self.type = type
        ...
        print('New character made')

    def write_to_csv(self):
        filename = 'character_file.csv'
        # write header if not already written
        if not os.path.exists(filename) or os.stat(filename).st_size == 0:
            with open(filename, 'w') as character_file:
                character_writer = csv.writer(character_file)
                character_writer.writerow(['Type', 'Name', 'Class', 'Health', 'Mana', 'Strength'])

        # write character line
        with open(filename, 'a') as character_file:
            fields = [self.type, self.name, self.character_class, self.health, self.mana, self.strength]
            character_writer = csv.writer(character_file)
            character_writer.writerow(fields)
            print(f"{self.name} added to the Character Sheet.")

【讨论】:

  • 太棒了,非常感谢@Sparkofska - 很享受。
猜你喜欢
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2016-10-20
  • 2012-06-21
  • 2021-04-23
相关资源
最近更新 更多