写在CSV文件的最顶行

时间:2016-06-15 00:51:31

标签: python python-2.7 csv

我有这个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循环期间的某个时刻写入outputfile的第一行,即当outputfile可能已经有条目时。

1 个答案:

答案 0 :(得分:4)

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

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