加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用dictwriter覆盖相同csv文件中的行

发布时间:2020-12-16 22:53:49 所属栏目:Python 来源:网络整理
导读:我有names.csv first_name,last_nameBaked,BeansLovely,SpamJohn,BangHarry,Potter 我想在同一个文件中用“jason statham”重命名“John Ban”. 我试图使用file.seek()但失败了 import csvwith open('/home/tiwari/Desktop/names.csv','rw+') as csvfile: fi

我有names.csv

first_name,last_name
Baked,Beans
Lovely,Spam
John,Bang
Harry,Potter

我想在同一个文件中用“jason statham”重命名“John Ban”.
我试图使用file.seek()但失败了

import csv
with open('/home/tiwari/Desktop/names.csv','rw+') as csvfile:
    fieldnames = ['first_name','last_name']
    writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
    reader = csv.DictReader(csvfile)
    for line,row in enumerate(reader):
        rs = sys.getsizeof(row)
        if row['first_name'] == 'John':
            csvfile.seek(-rs)
            writer.writerow({'first_name': 'Jason','last_name': 'statham'})
最佳答案
除非替换字符串与原始字符串的长度完全相同,否则您的方法将无效.

我建议读取所有行,并替换它们,并将其写回.

import csv

with open('/home/tiwari/Desktop/names.csv','r+') as csvfile:
    reader = csv.DictReader(csvfile)

    rows = []
    for row in reader:
        if row['first_name'] == 'John':
            row['first_name'] = 'Jason'
            row['last_name'] = 'Statham'
        rows.append(row)

    csvfile.seek(0)  # back to begining of the file.
    fieldnames = ['first_name',fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)
    csvfile.truncate()  # In case of updated content is shorter.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读