python-3.x - 在不删除所有内容的情况下修改 csv 文件的特定行的最佳方法是什么?
问题描述
我有一个用记事本打开的 csv 文件:
我想修改我的 csv 以将第 4 行替换为“温度水平波度”:
with open(file.csv, 'w') as m:
content = m.readlines()
line_4 = (content[3])
line_4.replace(line_4, 'Temperature Level Wave Degre')
我的 csv 是空的!
在不删除所有内容的情况下修改 csv 文件的特定行的最佳方法是什么?最有效的代码?
谢谢你。
解决方案
这是使用 python 的解决方案,但是正如我在评论中提到的,可能有更有效的命令行工具(我会使用awk
)
with open(filename, 'r+') as f:
lines = f.readlines() # read lines and store in list
lines[3] = 'Temperature Level Wave Degre\n' # change line 4, don't forget to add a newline
f.seek(0) # come back to beginning of file
f.writelines(lines) # write the new lines
f.truncate() # ensure we don't keep old stuff from the previous file
推荐阅读
- c# - Xamarin Forms 上的 ListView 仅在您重新保存 xml 页面时显示数据......知道吗?
- javascript - 如何在 React 中创建列表/详细信息视图
- encryption - TYPO3 加密的邮件链接(javascript:linkTo_UnCryptMailto)不适用于主题和正文
- javascript - 为什么 splice 从数组中删除所有元素?
- python - Python 无法识别基本的图形功能
- google-analytics - Google Analytics 自定义维度到 Google Ads 类似受众
- c++ - 为什么这个递归函数仍然会导致堆栈溢出?
- amazon-web-services - AWS CodeBuild:已安装 conda 但未找到
- javascript - d3js v6 读取多个 csv,Promise.all 返回 404
- mysql - MySQL 过去 14 天的移动平均线