【发布时间】:2019-10-15 03:23:27
【问题描述】:
给定一个像这样的输入文件data.dat:
# Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9
我需要在以“# aaa”开头的每一行上方添加不同的 cmets,所以它看起来像这样:
# Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9
我事先知道data.dat 文件中存在的“# aaa”cmets 的数量,但不知道它们的位置。
我有办法做到这一点(见下面的代码),但它相当复杂,而且根本没有效率。我需要将此代码应用于数百个大文件,因此我正在寻找一种有效的方法来执行此操作。
# Read file
with open("data.dat", mode="r") as f:
data = f.readlines()
# Indexes of "# aaa" comments
idx = []
for i, line in enumerate(data):
if line.startswith("# aaa"):
idx.append(i)
# Insert new comments in their proper positions
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for i, j in enumerate(idx):
data.insert(j + i, add_data[i])
# Write final data to file
with open("data_final.dat", mode="w") as f:
for item in data:
f.write("{}".format(item))
【问题讨论】:
标签: python list performance file-io