为什么 csv.DictWriter 只返回字典的最后一行?

时间:2021-02-14 21:52:49

标签: python csv dictionary

我对 python 非常陌生,我正在编写一个脚本来将一些数据移动到一个 CSV 文件中。数据取自字典,其中键是固定的,值是函数。这一切都在一个 for 循环迭代文件中,从中收集这些数据。

这是我试过的:

import os, csv

for folder, files in os.walk(directory):
    
     for file in files:
           def name(file):
                name = file.split(".", 1)[0]
           def type(file):
                if file.endswith("a"):
                   return("file_a")
                elif file.endswith("b"):
                   return("file_b")
           def size(file):
                size = os.path.getsize(os.path.join(directory,file))
           
           my_dict = {"name": name(file), "type": type(file), "size": size(file)}
      
           with open("csv_file.csv", "w", newline="") as csv_file:
                fieldnames = ("name", "type", "size")
                writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                writer.writeheader()
                writer.writerows(my_dict)

1 个答案:

答案 0 :(得分:0)

这里的问题是 writer.writeheader() 覆盖了整个文件。在每一行之后,你调用这个覆盖整个文件的函数,所以只有最后一行仍然存在

如评论中所述,实际问题是您在 for 循环的每次迭代中都使用 'w' 权限打开文件,但您希望追加到文件,因此简单地将 'w' 替换为 'a' 应该会给您想要的结果,但是,以下解决方案仍然是一种更简洁的方法!

import os, csv

# export opening of the CSV file outside of the loop
# that way it will only be opened once
# use "a" for "append" instead of "w" for write/overwrite
# when you want to add data to an existing file
with open("csv_file.csv", "w", newline="") as csv_file:
    fieldnames = ("name", "type", "size")
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    
    for folder, files in os.walk(directory):
        for file in files:
           def name(file):
               name = file.split(".", 1)[0]
           def type(file):
               if file.endswith("a"):
                   return("file_a")
               elif file.endswith("b"):
                   return("file_b")
           def size(file):
                size = os.path.getsize(os.path.join(directory,file))
           
           my_dict = {"name": name(file), "type": type(file), "size": size(file)}
           writer.writerows(my_dict)
相关问题