我有一个文本文件,用作模型的启动文件。它看起来像这样:
foo1
foo2
bar, foo, yolo
1, 2, 3
foo3
foo4
第3行是标题,第4行是值,两行都需要重复,具体取决于x的大小。假设x = 3.下面的行不应该被覆盖,而是向下移动。前面的行(foo1和foo2)是动态生成的,因此不一定只有两行,因此我不能只通过索引访问它们!
所以我的文件应该是这样的:
foo1
foo2
bar, foo, yolo
1, 2, 3
bar, foo, yolo
1, 2, 3
bar, foo, yolo
1, 2, 3
foo3
foo4
到目前为止我的想法:
initraw = open('fileX.txt', "r") #opening raw file for reading
initwrite= open('fileY.txt', "w") #opening file for writing
initline = initraw.readlines() #writing content of raw file into string
x = 3
for line in initline:
initwrite.writelines(line,)
if line.startswith('bar, foo, yolo'):
for i in range(x):
initwrite.writelines(initline[2])
initwrite.writelines(initline[3])
initwrite.close() #closing file
initraw.close() #closing raw file
有任何建议如何解决这个问题?现在,这看起来像这样:
foo1
foo2
bar, foo, yolo
bar, foo, yolo
1, 2, 3
bar, foo, yolo
1, 2, 3
1, 2, 3
foo3
foo4
所以我需要跳过“bar,foo,yolo”之后的第一行。
答案 0 :(得分:0)
希望这会有所帮助:
x = 2
lines = [[item] for item in initrow.split('\n')]
lines[2:4] = lines[2:4] * x
print lines
#will output [['foo1'], ['foo2'], ['bar, foo, yolo'], ['1, 2, 3'], ['bar, foo, yolo'], ['1, 2, 3'], ['foo3'], ['foo4']]
答案 1 :(得分:0)
initraw = open('fileX.txt', "r") #opening raw file for reading
initwrite= open('fileY.txt', "w") #opening file for writing
initline = initraw.readlines() #writing content of raw file into string
i = 0
for line in initline:
x = 3
i =+ 1
if line.startswith('bar, foo, yolo'):
for x in range(0, x-1):
initwrite.writelines(initline[i+1])
initwrite.writelines(initline[i+2])
initwrite.writelines(line)
initwrite.close() #closing file
initraw.close() #closing raw file