您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Python内联CSV文件编辑

使用Python内联CSV文件编辑

不,您不应该尝试写入当前正在读取的文件。你 可以@H_301_2@ 做,如果你继续seek读一排后掀背,但它是不可取的,尤其是如果你正在写回的数据比你读。

规范的方法是写入 新的临时@H_301_2@ 文件,然后将其移到读取的旧文件上。

from tempfile import NamedTemporaryFile
import shutil
import csv

filename = 'tmpEmployeeDatabase.csv'
tempfile = NamedTemporaryFile('w+t', newline='', delete=False)

with open(filename, 'r', newline='') as csvFile, tempfile:
    reader = csv.reader(csvFile, delimiter=',', quotechar='"')
    writer = csv.writer(tempfile, delimiter=',', quotechar='"')

    for row in reader:
        row[1] = row[1].title()
        writer.writerow(row)

shutil.move(tempfile.name, filename)

在这里利用tempfileshutil库来简化任务。

python 2022/1/1 18:43:36 有301人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶