python - 在 CSV 文件的最上面一行写入

标签 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 循环期间的某个时刻写入输出文件的第一行,即当输出文件可能已经有条目时。

最佳答案

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

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

关于python - 在 CSV 文件的最上面一行写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37824439/

相关文章:

python - 如何检测两个Python迭代器产生相同的项目?

python - 如何从 CSV 检查用户名和密码。文件

regex - 如何使用正则表达式替换标签内 csv 中的双引号

python - 使用 csv2rec 时 python 中的 matplotlib 库出错

python - 如何断言两个列表在 Python 中包含相同的元素?

python - 谷歌应用程序引擎(python)导入错误: No module named oauth2 in google app engine

python - 将现有模块更新到 Odoo 12 中的最新版本

python - 根据列名称在两列之间删除 pandas 数据框中的多列

python - 将 XPath 与 Scrapy 结合使用

python - 使用变量作为保存文件名 ~ im.save(type, '.png' )