考虑具有下列内容的.txt文件:
Pinus ponderosa P. & C. Lawson
var. scopulorum Engelm.
[5,800] - [7,800] 9,200 ft. [May] - [Jun]. Needleleaf
evergreen tree, mesophanerophyte; nanophyll, sclerophyll.
我想将任何以var.
开头的行附加到前一行
这是我的密码:
with open('myfile.txt', 'r') as f:
txt = ''
for line in f:
line = line.replace('\n', '')
if next(f)[:4] == 'var.':
txt = '{}\n{} {}'.format(txt, line, next(f))
这会引发以下错误:
Traceback (most recent call last): File "<stdin>", line 5, in <module> StopIteration
预期产出为:
Pinus ponderosa P. & C. Lawson var. scopulorum Engelm.
[5,800] - [7,800] 9,200 ft. [May] - [Jun]. Needleleaf
evergreen tree, mesophanerophyte; nanophyll, sclerophyll.
这是一种方法
Ex:
输出:
您可以一次完成它,而不是迭代行。此外,如果要编辑文件,请执行以下操作:
相关问题 更多 >
编程相关推荐