python - 如何使用python在csv文件中重复一行n次

标签 python

我是 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 进行此类文件操作的新手,并且在论坛上没有发现任何类似的问题。

谢谢

最佳答案

使用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)

关于python - 如何使用python在csv文件中重复一行n次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54896876/

相关文章:

python - "@"运算符在 Python 中起什么作用?

python - tkinter 中的循环按钮和功能分配

python - 使用 Python 从多个 URL 获取数据

Python多线程方法

python - 属性错误: module 'pandas.compat' has no attribute 'iteritems'

python - 如何在pytest中打印到控制台?

python - __init__ 括号里的东西叫什么?

python - 使用 scrapy 为一个 url 创建一个 csv 时输入

python - 每次运行这个程序时调用 datetime.now()

python - 为一个完整的模块定义 Python 装饰器