如何覆盖python中特定行的特定字符集

时间:2018-01-17 09:43:22

标签: python file character overwrite

所以,我试图创建一个程序,它将自动编辑文件中的一组特定字符(它将读取并替换它们)。没有其他数据可以在文件中移动,否则它可能会被破坏,所以我需要在与以前完全相同的位置替换文本。我环顾四周,没有发现任何有用的东西,但到目前为止,这是我的代码:

l = 3
w = 0
with open("InidCrd000.crd") as myfile:
    hexWord = myfile.readlines()[l].split()[w]
    codeA = hexWord[58]
    codeB = hexWord[59]
    print("Current value: ", codeA, codeB)
    codeA = " "
    codeB = "Ð"
    print("New value: ", codeA, codeB)

编辑 - 我现在有了这个代码(信用卡 - Ilayaraja),它可以正常工作,然后将文件分成行并将随机数据放在错误的位置(尽管输入的数据是正确的位置):

def replace(filepath, lineno, position, newchar):
    with open(filepath, "r") as reader:
        lines = reader.readlines()
        l = lines[lineno-1]
        l = l[0:position] + newchar + l[position+1:]
        lines[lineno-1] = l
    with open(filepath, "w") as writer:
        writer.writelines(lines)
replace("InidCrd000.crd", 4, 57, "")
replace("InidCrd000.crd", 4, 58, "Ð")

如果您想要测试文件,请点击此处:1drv.ms/u/s!AqRsP9xMA0g1iqMl-ZQbXUqX2WY8aA(它是onedrive文件)

2 个答案:

答案 0 :(得分:0)

首先使用以下代码查找要更改的代码:

l = 3
w = 0
with open("InidCrd000.crd") as myfile:
    hexWord = myfile.readlines()[l].split()[w]
    codeA = hexWord[58]
    codeB = hexWord[59]
myfile.close()

然后改变如下:

import fileinput

with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file:
    for line in file:
         line.replace(codeA, textToReplace)

答案 1 :(得分:0)

定义一个函数,其参数为文件路径(filepath),行号(lineno 1到N),行中字符的位置(position 0到N)和要覆盖的新字符(newchar)如下:

def replace(filepath, lineno, position, newchar):
    with open(filepath, "r") as reader:
        lines = reader.readlines()
        l = lines[lineno-1]
        l = l[0:position] + newchar + l[position+1:]
        lines[lineno-1] = l
    with open(filepath, "w") as writer:
        writer.writelines(lines)

您可以按如下方式调用该函数来替换字符:

replace("InidCrd000.crd", 3, 58, " ")
replace("InidCrd000.crd", 3, 59, "Ð")