简体   繁体   English

如何使用 fileinput 替换文件中一行的一部分?

[英]How to replace a portion of a line in a file using fileinput?

import fileinput

if number_of_bags.is_integer():
    with fileinput.FileInput('CoinCount.txt',inplace=True) as fileobj:
        for line in fileobj:
            x = line.split(',')
            for w, word in enumerate(x):
                if w == 3 and word == 'N':
                    print(line.replace('N', 'Y'), end='')
                    i = i + 1
                else:
                    i = i + 1

else:
    with fileinput.FileInput('CoinCount.txt',inplace=True) as fileobj:
        for line in fileobj:
            x = line.split(',')
            for w, word in enumerate(x):
                if w == 3 and word == 'Y':
                    print(line.replace('Y', 'N'), end='')
                    i = i + 1
                else:
                    i = i + 1

When I run this program, the text file is completely overwritten and all of its contents removed, each line is structured like this:当我运行这个程序时,文本文件被完全覆盖并删除了所有内容,每一行的结构如下:

Athena,£2,133.55,Y

I want this program to be able to go through each line (hence why the end shows i = i + 1 ) and replace the Y or N if it isn't supposed to be there (if the calculation is incorrect).我希望这个程序能够通过每一行 go (因此末尾显示i = i + 1 )并替换 Y 或 N 如果它不应该存在(如果计算不正确)。

How do I edit this code so that it doesn't remove the txt files data?如何编辑此代码以使其不删除 txt 文件数据?

There are several mistakes with how fileinput.FileInput is being used and the processing related to it is being done. fileinput.FileInput的使用方式以及与之相关的处理存在几个错误。

Something must be printed for each line of input if it is to be in the output.如果要在 output 中,则必须为每行输入打印一些内容。 However, after the x = line.split(',') the fourth word will contain either a 'Y\n' or a 'N\n' , so the following if w == 3 and word == 'N': or if w == 3 and word == 'Y': conditional be never be True .但是,在x = line.split(',')之后,第四个word将包含一个'Y\n'或一个'N\n' ,因此if w == 3 and word == 'N':或者if w == 3 and word == 'Y': conditional be never be True This means nothing is ever printed.这意味着什么都没有被打印出来。 This is why the result is an empty file.这就是结果是空文件的原因。

There's more than one way to fix things.解决问题的方法不止一种。 In the code below, the newline at the end of each line is removed with rstrip() before splitting it up into separate words.在下面的代码中,每行末尾的换行符在将其拆分为单独的单词之前使用rstrip()删除。 Doing that will make the testing for 'Y' or 'N' work so they can be replaced.这样做将使'Y''N'的测试工作,因此可以替换它们。 Then, regardless of whether the word was changed for not, the words are joined back together and a (possibly updated) line is print ed.然后,无论单词是否更改,单词都会重新连接在一起并print (可能更新的)行。

I also simplified the things so to make the whole thing shorter by not repeating so much of the code for the two possibilities.我还简化了这些事情,以便通过不为这两种可能性重复太多代码来使整个事情变得更短。

import fileinput


if number_of_bags.is_integer():
    target, replacement = 'N', 'Y'
else:
    target, replacement = 'Y', 'N'

line_to_process = 4

with fileinput.FileInput('CoinCount.txt', inplace=True) as fileobj:
    for line in fileobj:
        words = line.rstrip().split(',')
        if fileobj.lineno() == line_to_process:  # Only process the Nth line.
            if words[3] == target:
                words[3] = replacement
        print(','.join(words))

    numlines = fileobj.lineno()  # Number of lines processed.

print(f'Done, {numlines} lines processed')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM