如何在文件的奇数行中添加字符串?

时间:2019-06-15 05:13:41

标签: python python-3.x python-2.7

我试图用一些数组创建一个文件,并且我需要在文件的所有奇数行中添加一些数据。我还需要删除一些与.translate()

一起使用的字符
np.savetxt('new_arrary.txt', dsc)
mi_path = 'new_arrary.txt'
j = open(mi_path,'r')
lines = j.readlines()
j.close()
y = 0;
for i, line in enumerate(lines):
    if (i%2) != 0:
        lines[i-1] = str(kp[y])+' '+str(a[y])+' '+str(b[y])+' '+str(a[y])+' '+lines[i-1]
        y += 1
    lines[i] = lines[i].translate({ord('('): ord(' ')})
    lines[i] = lines[i].translate({ord(')'): None})
    lines[i] = lines[i].translate({ord('['): None})
    lines[i] = lines[i].translate({ord(']'): None})
    lines[i] = lines[i].translate({ord(','): None})

j = open(mi_path,'w')
for k in lines:
    j.write(k)
j.close()

与此同时,我正在修改行,但它跳过了一些行。 例如:代码先修改第1行,然后修改第5行,跳过第3行

1 个答案:

答案 0 :(得分:0)

您的代码引发类型错误,所以我建议这样:

import re

with open('oddlines.txt') as fp:
    text = fp.read()

text = text.replace('(', ' ')         # use .replace(..)
text = re.sub(r'[)[\],]', '', text)   # .. and re.sub(..) to remove characters
lines = text.split('\n')

for i in range(1, len(lines), 2):         # from 1, skip every other..
    lines[i-1] = 'prefix:' + lines[i-1]   # I don't know what your kp[y] etc. are, so I'm just adding a string prefix

for line in lines:                        # then either print to screen
    print line

with open('oddlines.out', 'w') as fp:     # or to file..
    fp.write('\n'.join(lines))

oddlines.txt中带有此文本:

first (line)
(second line)
th[i]rd line
fourth, line
fifth,line
first (line)
(second line)
th[i]rd line
fourth, line
fifth,line

上面的代码打印:

prefix:first  line
 second line
prefix:third line
fourth line
prefix:fifthline
first  line
prefix: second line
third line
prefix:fourth line
fifthline