如何删除紧随其后的空白行?

时间:2017-03-26 08:25:51

标签: python-3.x file delete-row

我有一个文件,我读了并做了一些动作。

export_comp_f = open(env_path +  '/girobo2/sim_export/modelsim/compile.do', 'r')
exp_cont = export_comp_f.readlines()
exp_cont = list(filter(lambda x: 'work/hdl' not in x, exp_cont)) 
exp_cont = list(map(lambda x: re.sub(r"^\".*?(\/2016\.2)", r'"$vivado_path/2016.2', x), exp_cont))
exp_cont = list(map(lambda x: re.sub(r"\+.*?(\/girobo2)", r'+incdir+$env_path/girobo2', x), exp_cont))
exp_cont = list(map(lambda x: re.sub(r"\"\w\:.*?(\/girobo2)", r'"$env_path/girobo2', x), exp_cont))
exp_cont = exp_cont[:-5]
exp_cont.append('vlog -work xil_defaultlib "glbl.v"\n')
export_comp_f.close()

我想删除任何包含以" vcom"开头的行。在它之后有一个空白行。

例如:

**vcom -work lib_pkg_v1_0_2 -64 -93 \**  //should be deleted


vcom -work lib_fifo_v1_0_5 -64 -93 \
"$env_path/girobo2/syn/syn.ip_user_files/ipstatic/lib_fifo_v1_0/hdl/src/vhdl/async_fifo_fg.vhd" \
"$env_path/girobo2/syn/syn.ip_user_files/ipstatic/lib_fifo_v1_0/hdl/src/vhdl/sync_fifo_fg.vhd" \

1 个答案:

答案 0 :(得分:0)

也许是这样的?

line = ['vcom -work lib_pkg_v1_0_2 -64 -93 \  //should be deleted',
'',
'',
'vcom -work lib_fifo_v1_0_5 -64 -93 ',
'"$env_path/girobo2/syn/syn.ip_user_files/ipstatic/lib_fifo_v1_0/hdl/src/vhdl/async_fifo_fg.vhd" ',
'"$env_path/girobo2/syn/syn.ip_user_files/ipstatic/lib_fifo_v1_0/hdl/src/vhdl/sync_fifo_fg.vhd" ']

output = []
for i in range(len(line) - 1):
    if line[i][:4] == "vcom" and line[i + 1].strip() == "":
        pass
    else:
        output.append(line[i])

print(output)

如果您希望修改原始line,则代码会变短。

for i in range(len(line) - 1):
    if line[i][:4] == "vcom" and line[i + 1].strip() == "":
        line[i] = None

line = [item for item in line if item is not None]
print(line)