如何使用Python编写csv中的第n行?



我有以下问题。假设我想在cell上写一个单词column = 1 &和row = 3.

我写了这个函数:

import csv
def write_to_csv(myfile, word):
with open(myfile, "w", newline="") as csv_file:
csv_writer = csv.writer(csv_file)
write = [word]
csv_writer.writerow(elt for elt in write)
write_to_csv("output.csv", "hello")

我的函数写单词"hello"进入column = 1 &And row = 1.

现在假设我的output.csv在第一个单元格中已经有了一些内容。我不想重写它。那么我该如何修改我的函数来写单词hello;On column = 1 &And row = 3 ?

我发现了这个问题,但它没有帮助我:如何使用python选择CSV文件中的每第n行

非常感谢!

CSV文件是文本文件。这意味着您不应该尝试在适当的位置覆盖它。常见的方法是将其复制到一个新文件中,并在此时引入您的更改。完成后,使用旧名称移动新文件。

这是一个可能的代码。它只希望output.csv.tmp文件不存在,但可以创建,并且output.csv至少有4行:

def write_to_csv(myfile, word, row_nb, col_nb):
"""Updates a csv file by writing word at row_nb row and col_nb column"""
with open(myfile) as csv_file, open(myfile+'.tmp', "w", newline='') as out:
csv_reader = csv.reader(csv_file)
csv_writer = csv.writer(out)
#skip row_nb rows
for i in range(row_nb):
csv_writer.writerow(next(csv_reader))
# read and change the expected row
row = next(csv_reader)
row[col_nb] = word
# print(row)              # uncomment for debugging
csv_writer.writerow(row)
# copy last rows
for row in csv_reader:
csv_writer.writerow(row)
# rename the tmp file
os.remove(myfile)
os.rename(myfile+'.tmp', myfile)
# write hello at first column of fourth row in output.csv
write_to_csv('output.csv', 'hello', 3, 0)

最新更新