如何在Python中复制特定行

时间:2018-04-08 17:09:13

标签: python

import sys
from math import log
import datetime
import numpy as np
from itertools import repeat


x = 1 
y = 2 

z= 24

T=int(z/(x+y))

with open('A.txt', 'r') as f:
    lines = f.readlines()

with open('A.txt', 'w') as f:
    for i,line in enumerate(lines):
        if i==10:
                f.write(str("Papa")+'\n')
                f.write(str(x)+ "*31 /"+'\n')
                f.write(str("Mama")+'\n')
                f.write(str(y)+ "*31 /"+'\n')
                [x for item in lines for x in repeat(item, T)]
        else:
                f.write(line)
        previous_line = line

这是我的代码,运行正常没有任何错误,但它没有给我任何结果

我试图根据T来实现重复行,因为这里的T等于8,所以输出看起来像:

Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31

如何让代码像这样工作?

2 个答案:

答案 0 :(得分:2)

删除列表理解。使用循环

if i==10:
    for _ in range(T):
        f.write('Papa\n{}*31 /\nMama\n{}*31 /\n'.format(x, y))

或者,您正在寻找

item = """Papa
{}*31 /
Mama
{}*31 /""".format(x, y) 

for x in repeat(item, T):
    f.write(x)

或更好

f.writelines(repeat(item, T)) 

答案 1 :(得分:0)

from itertools import repeat

x = 1 
y = 2 

z= 24

T=int(z/(x+y))

# dont have your file, creating a dummy data read in
if lines is None:
    lines = list(map(str,range(20)))

with open('A.txt', 'w') as f:
    for i,line in enumerate(lines):
        if i==10:

            # create the text and write it into the file 
            # using repeat it and writelines (writes multiple lines at once) 
            f.writelines(repeat(f'Papa\n{x}*31\nMama\n{y}*31\n',T)) 
        else:
            f.write(line+"\n")

with open('A.txt', 'r') as f:
    for l in f:
        print(l, end = "") 

输出:

0
1
2
3
4
5
6
7
8
9
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
Papa
1*31
Mama
2*31
11
12
13
14
15
16
17
18
19