不,您不应该尝试写入当前正在读取的文件。你 可以@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)