我试图用一些数组创建一个文件,并且我需要在文件的所有奇数行中添加一些数据。我还需要删除一些与.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行
答案 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