python - 在 Python 中附加到 .csv 文件

标签 python csv

我正在尝试使用 Python 写入现有的 .csv 文件,但我不想将数据附加到现有文件的底部,而是想将新信息附加到 .csv 文件的新列。这样做的原因是我想“无限”循环读取代码的数据部分,然后将每次循环迭代期间读取的数据添加到新列而不是行。本质上,我想要如下内容:

Row1Iteration1, Row1Iteration2, Row1Iteration3,..., Row1IterationX
Row2Iteration1, Row2Iteration2, Row2Iteration3,..., Row2IterationX
Row3Iteration1, Row3Iteration2, Row3Iteration3,..., Row3IterationX
Row4Iteration1, Row4Iteration2, Row4Iteration3,..., Row4IterationX
Row5Iteration1, Row5Iteration2, Row5Iteration3,..., Row5IterationX

代替:

Row1Iteration1
Row2Iteration1
Row3Iteration1
Row4Iteration1
Row5Iteration1
Row1Iteration2
Row2Iteration2
Row3Iteration2
etc...

有谁知道这样做的方法,或者这是 .csv 文件的不可能约束?除了 .csv 之外,还有其他方法可以让我在执行此操作的同时仍然使用 Excel 进行操作吗?

最佳答案

希望这个例子对你有帮助:

# of course you should read the file someway
s = """
Row1Iteration1, Row1Iteration2, Row1Iteration3
Row2Iteration1, Row2Iteration2, Row2Iteration3
Row3Iteration1, Row3Iteration2, Row3Iteration3
Row4Iteration1, Row4Iteration2, Row4Iteration3
Row5Iteration1, Row5Iteration2, Row5Iteration3
"""
ncols = 3

iterations = []
for line in s.strip().split('\n'):
    iterations.append([l.strip() for l in line.split(',')])

with open('output.csv', 'w') as out:
    for col in xrange(ncols):
        for it in iterations:
            print it[col]
            out.write(col)

关于python - 在 Python 中附加到 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13349378/

相关文章:

python - 在python列表中填充缺失数据

excel - 高效地从 .xlsx 电子表格中提取工作表名称

csv - 当Jmeter的响应数据是XML格式时,在输出的CSV文件中我们生成的内容是不可读的形式。如何克服它

php - 如果 key 不存在则发送 null

python - 在 python 中使用 csv 文件并输出 json

python - 如何在 mysqldb 中获取 num 个结果

Python MyHashTable 类 : search method with linear probing

r - 是否有任何正当理由不使用 fread() 和 fwrite() 而不是 read.csv() 和 write.csv()?

python - 计算出平均值

python - 如何解决由FFT驱动的微分程序中的移位和缩放错误?