简体   繁体   English

如何在新行中制作每个数据 [data to csv]?

[英]How can I make each data in new row [data to csv]?

Each data is in 1 row and 1 column.每个数据在 1 行和 1 列中。 I want to separate them in csv file我想在 csv 文件中将它们分开

from dataclasses import field, fields
import os
import csv
import collections
y=[]
Dict_New=[]
a=['Name','Count']
d={}
path = r"C:\Users\piotr\Desktop\CV"
files = os.listdir(path)
files_file = [f for f in files if os.path.isfile(os.path.join(path, f))]
print(files_file)   # ['file1', 'file2.txt', 'file3.jpg']
for x in files_file:
   y.append(x[:-4])
print(y)
Counter=collections.Counter(y)
print(Counter)
for key, values in Counter.items():
    Dict_New.append({'Name': key, "Count": values})
print(Dict_New)
with open ("test.csv",'w') as f:
    write = csv.DictWriter(f,fieldnames=a)
    write.writeheader()
    write.writerows(Dict_New)

I don't know why data are not separte in each row我不知道为什么每一行的数据都不是separte

csv docs stipulates you should provide newline='' when working with files, observe how opening is done incsv.DictWriter example csv文档规定在处理文件时应该提供newline='' ,观察csv.DictWriter示例中的打开方式

with open('names.csv', 'w', newline='') as csvfile:

this does apply also to csv.writer and csv.reader and allow code to work correctly indepedent from used ends of line.这也适用于csv.writercsv.reader并允许代码独立于使用的行尾正确工作。

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

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