我可以使用 Python 的 CSV 库或类似技术修改 CSV 文件吗?
当前我正在处理一个文件并更新第一列(名称字段)以更改格式。我的代码的简化版本如下所示:
with open('tmpEmployeeDatabase-out.csv', 'w') as csvOutput:
writer = csv.writer(csvOutput, delimiter=',', quotechar='"')
with open('tmpEmployeeDatabase.csv', 'r') as csvFile:
reader = csv.reader(csvFile, delimiter=',', quotechar='"')
for row in reader:
row[0] = row[0].title()
writer.writerow(row)
哲学是有效的,但我很好奇我是否可以进行内联编辑,这样我就不会复制文件。
我已经尝试过以下操作,但这会将新记录附加到文件的末尾,而不是替换它们。
with open('tmpEmployeeDatabase.csv', 'r+') as csvFile:
reader = csv.reader(csvFile, delimiter=',', quotechar='"')
writer = csv.writer(csvFile, delimiter=',', quotechar='"')
for row in reader:
row[1] = row[1].title()
writer.writerow(row)