3

我正在尝试使用 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 进行操作吗?

4

3 回答 3

2

这在我所知道的任何系统或文件类型上都是不可能的。您必须读取数据,对其进行操作并保存/覆盖原始文件。这就是文件 I/O 在几乎任何操作系统上的工作方式。您可以读取文件,(覆盖)写入文件并附加到文件末尾,仅此而已。

如果您的文件非常大,您可以逐个读取它,进行操作并将其写入临时文件。完成后,可以将原始文件替换为新的临时文件。

于 2012-11-12T18:45:05.197 回答
2

我希望这个例子可以帮助你:

# 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)
于 2012-11-12T19:37:13.757 回答
0

正如钦梅所说,您最好的选择可能是读取 csv 文件,对其进行按摩,然后将其输出回 csv。看一下这个 stackoverflow 讨论,它似乎解决了与您所问问题类似的问题。

于 2012-11-12T18:56:44.660 回答