简体   繁体   English

如何在不使用fileinput的情况下更改python中的一行?

[英]How to change a line in python without using fileinput inplace?

I want to replace a character on every line when the line match with my lookup_keyword. 当该行与我的lookup_keyword匹配时,我想在每行上替换一个字符。 I managed to came up with below solutions. 我设法提出了以下解决方案。 But the finaljoin only write the changes on the new file (only affected line is being written back) 但是finaljoin将更改写在新文件上(只写回受影响的行)

How can I write unaffected line together in a new file? 如何在新文件中一起写入未受影响的行?

I know that we can use fileinput inplace editing but that more suitable for keyword replacing. 我知道我们可以使用fileinput就地编辑,但这更适合于关键字替换。

Example input file,
123456789 [Thanos]
123456789 [Thanos]
123456789 [Thor]
123456789 [Loki]

Example output file,
1AA345KK789 [Thanos]
1AA345KK789 [Thanos]



Expected output file that I actually wanted.
1AA345KK789 [Thanos]
1AA345KK789 [Thanos]
123456789 [Thor]
123456789 [Loki]




lookup_keyword= "Thanos"

with open(filename) as myFile:
    # myFile,1 means start reading the line at line number one.
    # By default python will read start from 0.
    for num, line in enumerate(myFile, 1):
        if lookup_keyword in line:
            #print ('Found at line:', num)
            s = list(line)
            s[1] = 'AA'
            s[5] = 'KK'

            # join the list to a original string form
            finaljoin = "".join(s)

            #print (finaljoin)
            with open(new_filename, 'a+') as f:
                f.write(finaljoin)

The output file will only contain lines that you actually write to it. 输出文件将仅包含您实际写入的行。

If Thanos is in the line, you modify the line, open the output file, and append the changed line to it. 如果Thanos在该行中,请修改该行,打开输出文件,然后将更改后的行附加到该行。

But if not, you do nothing, so nothing gets written. 但是,如果没有,您什么也不做,所以什么也没写。

You could fix it like this: 您可以这样解决:

for num, line in enumerate(myFile, 1):
    #print ('Found at line:', num)
    s = list(line)
    if lookup_keyword in line:
        s[1] = 'AA'
        s[5] = 'KK'
    # join the list to a original string form
    finaljoin = "".join(s)

    #print (finaljoin)
    with open(new_filename, 'a+') as f:
        f.write(finaljoin)

That way, you're always creating a new line and appending it to the new file, whether you modified it or not. 这样,无论是否修改它,您总是在创建新行并将其附加到新文件中。

Alternatively: 或者:

for num, line in enumerate(myFile, 1):
    if lookup_keyword in line:
        #print ('Found at line:', num)
        s = list(line)
        s[1] = 'AA'
        s[5] = 'KK'

        # join the list to a original string form
        finaljoin = "".join(s)
    else:
        finaljoin = line
    with open(new_filename, 'a+') as f:
        f.write(finaljoin)

That way you're not wasting effort splitting and rejoining the line when you don't want to modify it, and it's not that much more complicated. 这样,当您不想修改它时,您就不会浪费精力去拆分和重新加入该行,而且没有那么复杂。

input_file.txt input_file.txt

Example input file,
123456789 [Thanos]
123456789 [Thanos]
123456789 [Thor]
123456789 [Loki]    

Script.py 脚本

input_file_name = 'input_file.txt'
output_file_name = 'output_file.txt'

lookup_keyword= "Thanos"

with open(input_file_name) as input_file:
    next(input_file)        # skip first line
    with open(output_file_name, 'w') as output_file:
        for input_line in input_file:
            if lookup_keyword in input_line:
                input_list = list(input_line)
                input_list[1] = 'AA'
                input_list[5] = 'KK'

                output_line = ''.join(input_list)
            else:
                output_line = input_line

            output_file.write(output_line) 

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

相关问题 如何使用 fileinput 替换文件中一行的一部分? - How to replace a portion of a line in a file using fileinput? python fileinput行尾 - python fileinput line endings 如何在 python 中使用 fileinput.input 获取每一行的值 - how can I get the values of each line using fileinput.input in python 在 Python 如何在不使用文件输入模块的情况下从文件中删除一系列行 - In Python how to remove a range of lines from a file without using fileinput module 使用 python 文件输入模块时跳过第一行的优雅方法? - Elegant way to skip first line when using python fileinput module? python 文件输入查找和替换行 - python fileinput find and replace line 如果无法使用Python fileinput.FileInput(…)在文本文件中添加一行,则无法尝试添加该行 - Having trouble trying to add a line to a text file if that line doesn't exist already using Python fileinput.FileInput(…) 如何使用 fileinput 替换一行中的段 - How do you replace segments in a line using fileinput 如何使用从某一行开始的文件输入替换文本 - How to replace text using fileinput starting from a certain line 如何使用python中的fileinput保存文件? 给AttributeError:'FileInput'对象没有属性'read' - How to save the file using fileinput in python? Giving AttributeError: 'FileInput' object has no attribute 'read'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM