写入 CSV 文件的最上面一行

pyt*_*ice 2 python csv python-2.7

我有这个 sample.csv 文件:

a   1   apple
b   2   banana
c   3   cranberry
d   4   durian
e   5   eggplant
Run Code Online (Sandbox Code Playgroud)

并有以下代码:

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

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

Ani*_*non 5

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

with open("sample.csv", "a") as fp:
     fp.write("new text")
Run Code Online (Sandbox Code Playgroud)

如果要覆盖文件:

with open("sample.csv", "w") as fp:
     fp.write("new text")
Run Code Online (Sandbox Code Playgroud)

如果要从文件中删除一行

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)
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)