我想从一个文件中复制两个特定字符串之间的行,然后将它写入相同两个字符串之间的另一个文件。这是我到目前为止尝试的代码:
with open("verilog.v","r") as rf_VamsModel, open("verilog.sv", 'w+') as wf_sytemVerilogFile:
copy = False
write= False
for vline in rf_VamsModel:
if vline.strip() == "//Start of functional specification here":
copy = True
elif vline.strip() == "//End of functional specification here":
copy = False
elif copy:
for svline in wf_sytemVerilogFile:
if svline.strip() == "//Start of functional specification here":
write = True
elif svline.strip() == "//End of functional specification here":
write = False
elif write:
wf_sytemVerilogFile.write(vline)
但这不起作用,写文件verilog.sv为空,没有内容。我尝试追加而不是写,但它也没有用。
此外,我想修改代码,以便当它在写入文件中找到匹配的行(write == True)时,它会在匹配后忽略立即空行,并且在匹配后也会忽略以comments(//)开头的任何行。然后开始追加所有匹配的行,直到它在write == False时找到匹配。
答案 0 :(得分:0)
以下是我自己做的方式。 此代码可用于将两个特定字符串/行之间的行从一个文件复制到另一个文件。只有在写入文件中已存在类似的行时,它才会将这些行写入另一个文件:
with open("verilog.v","r") as rf_VamsModel:
copy = False
write= False
for vline in rf_VamsModel:
if vline.strip() == "//Start of functional specification here":
copy = True
elif vline.strip() == "//End of functional specification here":
copy = False
elif copy:
wtstring=wtstring+vline #wtstring has the functional code between two lines which you want to write to .sv file
with open("verilog.sv", "r+") as wf_sytemVerilogFile:
insert=False
contents=wf_sytemVerilogFile.readlines()
for index, svline in enumerate(contents):
if svline.strip() == "//End of functional specification here":
wtindex=index
insert=True
break
contents.insert(wtindex,wtstring) #contents has complete code in list format, functional code is copied from VAMS model into SV model
stringContents="".join(contents) #convert list into string in order to write it to .sv file
if insert:
wf_sytemVerilogFile.seek(0,0)
wf_sytemVerilogFile.write(str(stringContents))
else:
print("did not write since insert==False")