簡體   English   中英

在python中重新格式化.csv:連續計算逗號,並在特定數量的逗號后插入換行符

[英]Reformat .csv in python: count commas in a row and insert line break after specific number of commas

我是python的新手,正在尋找重新格式化.csv文件格式的腳本。 因此,在我的.csv文件中,存在格式不正確的行。 它看起來確實與此類似:

id,author,text,date,id,author,
text,date
id,author,text,date
id,author,text,date

應該在每行上包含“ id,author,text,date”。 因此,我的想法是對每行中的逗號進行計數,當達到特定數字時(在本示例中為4),它將在下一行的開頭插入其余部分。 我得到的是將逗號分隔為一行的以下內容:

import csv
with open("test.csv") as f:
    r = csv.reader(f) # create rows split on commas
    for row in r:
        com_count = 0
        com_count += len(row)
        print(com_count)

謝謝你的幫助!

我們將構建一個生成條目的生成器,然后從中生成新行

with open('oldfile.csv', newline='') as old:
    r = csv.reader(old)
    num_cols = int(input("How many columns: "))
    entry_generator = (entry for row in r for entry in row)
    with open('newfile.csv', 'w+', newline='') as newfile:
        w = csv.writer(newfile)
        while True:
            try:
                w.writerow([next(entry_generator) for _ in range(num_cols)])
            except StopIteration:
                break

如果您的行缺少條目,則無法使用。

如果要以編程方式處理獲取列寬,則可以將其包裝在以寬度為輸入的函數中,也可以將csv的第一行用作規范長度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM