gpt4 book ai didi

python - 如何将字符串添加到文件中的奇数行?

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:00 25 4
gpt4 key购买 nike

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

最佳答案

您的代码引发类型错误,因此我建议如下:

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

关于python - 如何将字符串添加到文件中的奇数行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56607552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com