简体   繁体   English

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

[英]Why csv.DictWriter is returning only the last row of the dictionary?

I am really new at python and I'm writing a script to move some data to a CSV file.我是 python 的新手,我正在编写一个脚本来将一些数据移动到 CSV 文件中。 Data are taken from a dictionary where keys are fixed and values are functions.数据取自字典,其中键是固定的,值是函数。 This is all inside a for loop iterating files from which those data are collected.这一切都在一个for循环迭代文件中,从这些文件中收集这些数据。

This is what I've tried:这是我尝试过的:

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)

The issue here is that writer.writeheader() overwrites the entire file. 这里的问题是 writer.writeheader()覆盖了整个文件。 After each row, you are calling this function that overwrites the entire file, so only the last row will still be there at the end . 在每一行之后,您将调用此 function 覆盖整个文件,因此只有最后一行仍然存在于末尾

As mentioned in the comments, the actual issue is that you are opening the file with 'w' permissions in every iteration of the for loop, but you would want to append to the file, hence simply replacing 'w' by 'a' should give you the wanted result, however, the following solution is still a cleaner approach!如评论中所述,实际问题是您在 for 循环的每次迭代中都以'w'权限打开文件,但您希望append到该文件,因此只需将'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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM