我想循环遍历文本文件的内容,并在某些行上进行搜索和替换,并将结果写回文件.我可以先将整个文件加载到内存中然后再写回来,但这可能不是最好的方法.
在以下代码中,最好的方法是什么?
f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
Run Code Online (Sandbox Code Playgroud) 是否可以在 CSV 文件的第二行插入新行?例如,我有一个包含列名称及其值的 CSV:
meter_id, sdp_id, lat, lon
813711, 1331, 34.298, -83.113
Run Code Online (Sandbox Code Playgroud)
我尝试读取此文件的应用程序需要添加一个新行来指示列类型。在上面的示例中,所有内容都是字符串,因此 CSV 需要是:
meter_id, sdp_id, lat, lon
String, String, String, String
813711, 1331, 34.298, -83.113
Run Code Online (Sandbox Code Playgroud)
我读过几篇如何在 CSV 末尾添加新行的文章,但找不到有关如何执行上述操作的任何内容。
首先感谢帮助我移动文件和帮助我使用tcl脚本.
小疑问我有python代码..如下所示..
import os
import shutil
data =" set filelid [open \"C:/Sanity_Automation/Work_Project/Output/smokeTestResult\" w+] \n\
puts $filelid \n\
close $filelid \n"
path = "C:\\Sanity_Automation\\RouterTester900SystemTest"
if os.path.exists(path):
shutil.rmtree('C:\\Sanity_Automation\\RouterTester900SystemTest\\')
path = "C:\\Program Files (x86)"
if os.path.exists(path):
src= "C:\\Program Files (x86)\\abc\\xyz\\QuickTest\\Scripts\\RouterTester900\\Diagnostic\\RouterTester900SystemTest"
else:
src= "C:\\Program Files\\abc\\xyz\\QuickTest\\Scripts\\RouterTester900\\Diagnostic\\RouterTester900SystemTest"
dest = "C:\\Sanity_Automation\\RouterTester900SystemTest\\"
shutil.copytree(src, dest)
log = open('C:\\Sanity_Automation\\RouterTester900SystemTest\\RouterTester900SystemTest.app.tcl','r+')
log_read=log.readlines()
x="CloseAllOutputFile"
with open('C:\\Sanity_Automation\\RouterTester900SystemTest\\RouterTester900SystemTest.app.tcl', 'a+') as fout:
for line in log_read:
if x in line:
fout.seek(0,1)
fout.write("\n")
fout.write(data)
Run Code Online (Sandbox Code Playgroud)
此代码用于将文件从一个位置复制到另一个位置,在特定文件中搜索关键字并将数据写入文件正在运行...
我的疑问是每当我写的..它写到文件末尾而不是当前位置...
示例:说..我将文件从程序文件复制到sanity文件夹,并在其中一个复制文件中搜索单词"CloseAllOutputFile".当找到单词时,它应该在该位置插入文本而不是文件末尾.