【问题标题】:Writing on the topmost row of a CSV file在 CSV 文件的最上面一行写入
【发布时间】:2016-10-15 22:04:07
【问题描述】:

我有这个 sample.csv 文件:

a   1   apple
b   2   banana
c   3   cranberry
d   4   durian
e   5   eggplant

并有如下代码:

samplefile = open(sample.csv,'rb')
rows = samplefile .readlines()
outputfile = open(output.csv,'wb')
wr = csv.writer(outputfile)
for row in rows:
     wr.writerow(row)

我想要的是在 for 循环期间的某个时间点写入输出文件的第一行,即当输出文件可能已经有条目时。

【问题讨论】:

  • 在写入之前确定要写入 output.csv 的内容更容易
  • 是的,我明白了,只是在想这种方式是否可行。谢谢你:)
  • 无法做到:Here is a link 来列举这个话题。
  • @Bhargav Rao 该链接可能会提供其他方式,并可用于进一步改进该过程,让我仔细研究一下,并尝试确定它是否与我想要的相同。谢谢。

标签: python python-2.7 csv


【解决方案1】:

如果要添加到文件的末尾(追加到它):

with open("sample.csv", "a") as fp:
     fp.write("new text")

如果你想覆盖文件:

with open("sample.csv", "w") as fp:
     fp.write("new text")

如果你想remove a line from file:

import fileinput
import sys

for line_number, line in enumerate(fileinput.input('myFile', inplace=1)):
  if line_number == 0:  #first line
    continue
  else:
    sys.stdout.write(line)

如果要添加新的第一行(在现有行之前):

with open("sample.csv", "r+") as fp:
     existing=fp.read()
     fp.seek(0) #point to first line
     fp.write("new text"+existing) # add a line above the previously exiting first line

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    相关资源
    最近更新 更多