[英]Python: Read in specific lines from a file and replace a specific character on those lines and save file
New to python and can't find the answer for this problem. 新的python并没有找到这个问题的答案。 I have a file similar to this: 我有一个类似这样的文件:
@BNNDSIJHF @BNNDSIJHF
ABCDABCDAB ABCDABCDAB
& &
*&ABDA&&# * ABDA &&#
There are four lines of data for an object. 对象有四行数据。 There are 1000's of objects in the file, so there are 4*objects in the file. 文件中有1000个对象,因此文件中有4个对象。 I need to replace all the Bs with Xs, but only on line 2 of each object. 我需要用X替换所有B,但只在每个对象的第2行。 Ex. 防爆。
@BNNDSIJHF @BNNDSIJHF
AXCDAXCDAX AXCDAXCDAX
& &
*&ABDA&&# * ABDA &&#
Even though the last line of the object has Bs in it, they don't get replaced. 即使对象的最后一行有Bs,它们也不会被替换。 Here's what I've tried: 这是我尝试过的:
import sys
import os
def open_and_replace(filename):
with open(filename) as read_file:
temp = open("/tmp/temp.txt","w")
for index,line in enumerate(read_file,1):
if index == 2:
temp.write(line.replace('B', 'X'))
index=index+4
else:
temp.write(line.strip() + "\n")
temp.close()
os.rename("/tmp/temp.txt",filename)
for file_name in sys.argv[1:]:
open_and_replace(file_name)
This replaces the all the B's in the file past line 2. Any help would be appreciated! 这将取代过去第2行文件中的所有B.任何帮助将不胜感激!
IIUC, if you have a list of lines with no whitespaces IIUC,如果你有一个没有空格的行列表
[x for x in f.readlines() if x.strip()]
such as 如
['@BNNDSIJHF',
'ABCDABCDAB',
'&',
'*&ABDA&&#',
'@BNNDSIJHF',
'ABCDABCDAB',
'&',
'*&ABDA&&#']
You can just use a for loop starting at 2nd line with a step of 4, which is the fixed length of every object. 您可以使用从第2行开始的for循环,步长为4,这是每个对象的固定长度。
for i in range(1, len(ll), 4):
ll[i] = ll[i].replace('B', 'X')
Then just '\\n'.join
save it back to a file 然后只需'\\n'.join
将其保存回文件
您应该将if index == 2
语句更改为if index % 4 == 2
,并删除index=index+4
行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.