写在CSV文件的最上面一行 [英] Writing on the topmost row of a CSV file

查看:1011
本文介绍了写在CSV文件的最上面一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个sample.csv档案:

I have this sample.csv file:

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可能已经有条目。 / p>

What I wanted to to is write on the first row of outputfile at some point during the for loop, i.e. when outputfile may already have entries.

推荐答案

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

If you want to add to the end of the file(append to it):

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

如果要覆盖文件:

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

如果您要从文件中删除一行

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)

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

If you want to add a new first line(before the existing one):

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

这篇关于写在CSV文件的最上面一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆