如何编辑此替换代码以仅替换n行



我正在处理的代码本质上应该进入一个文件('Coincount.txt'(,对于第n行,如果第4部分(因此是第3部分(的字符串等于名为'target'的变量,则用替换项替换第4部分。

import fileinput
if number_of_bags.is_integer():
target, replacement = 'N', 'Y'
else:
target, replacement = 'Y', 'N'
with fileinput.FileInput('CoinCount.txt', inplace=True) as fileobj:
for n,line in enumerate(fileobj):
words = line.rstrip().split(',')
if words[3] == target:
words[3] = replacement
print(','.join(words))
f = fileobj.lineno()  # Number of lines processed.
i = i + 1
print(f'Done, {f} lines processed')

还请知道,txt文件是这样设计的:

Abena,5p,325.00,Y
Malcolm,1p,3356.00,Y
Jane,£2,120.00,Y
Andy,£1,166.25,N
Sandip,50p,160.00,Y
Liz,20p,250.00,Y
Andy,20p,250.00,Y
Andy,50p,160.00,Y
Jane,£1,183.75,N

第4部分表示"Y"或"N">

这也是一个更大函数的一部分,但你需要知道的是,numberof_backs是被扫描行的一个变量,这就是它的工作原理。

请告诉我我需要如何重组这个代码或在其中实现一个新行,以便它正常工作。

现在,如果我输入这个,txt文件中的输出是:

Abena,5p,325.00,Y
Malcolm,1p,3356.00,Y
Jane,£2,120.00,Y
Andy,£1,166.25,Y
Sandip,50p,160.00,Y
Liz,20p,250.00,Y
Andy,20p,250.00,Y

这是由于CCD_ 1将行的所有第4部分替换为CCD_。我想知道如何让这个函数只针对第n行,这样每一行都会替换第4部分,或者如果已经正确输入,就离开它。

如果我答对了你的问题,你只想更改一行,所以假设你有这个:

line_to_replace = 3 # var that will incidate what line you want to change

这样你就可以更改你的代码:

for n,line in enumerate(fileobj):

进入:

for n,line in enumerate(fileobj):
if n == line_to_replace: # simple if to check the current line number
...code...

最新更新