【问题标题】:how to repeat a row n number of times in a csv file using python如何使用python在csv文件中重复一行n次
【发布时间】:2019-02-27 01:57:46
【问题描述】:

我是 python 新手,正在尝试将多个文件合并到所需的布局中。 我的一个问题涉及重复 csv 文件的每一行(不包括标题)n 次。例如

初始文件:

header1 header2 header3
abc       123    a1
def       456    b1
ghi       789    c1

修改后的文件应该是这样的(例如3次重复):

header1 header2 header3
abc       123    a1
abc       123    a1
abc       123    a1
def       456    b1
def       456    b1
def       456    b1
ghi       789    c1
ghi       789    c1
ghi       789    c1

使用 csv 或 pandas 在 python 中执行此操作的最佳方法是什么。 如果问题太琐碎,我深表歉意,但我是使用 python 进行此类文件操作的新手,在论坛上没有发现任何类似的问题。

谢谢,

【问题讨论】:

标签: python


【解决方案1】:

使用csv模块,你可以这样做:

import csv

with open('out.txt', 'w') as fout, open('in.txt', 'r') as fin:
        reader = csv.reader(fin)
        writer = csv.writer(fout)
        writer.writerow(next(reader))
        for l in reader:
            for i in range(3):
                writer.writerow(l)

【讨论】:

    【解决方案2】:

    3次,你可以这样做:

    three_df = pd.concat([df,df,df])
    

    您可以轻松编写一个循环执行 n 次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-02
      • 2020-10-16
      • 2020-08-10
      • 2023-03-23
      • 2020-06-02
      • 2020-01-12
      • 1970-01-01
      • 2012-12-04
      相关资源
      最近更新 更多