【问题标题】:How to overwrite a specific set of characters from a specific line in python如何覆盖python中特定行的特定字符集
【发布时间】:2018-06-26 03:30:10
【问题描述】:

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

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文件)

【问题讨论】:

  • 你能从输入文件中显示一个sn-p吗?
  • 这是一个小的 sn-p(文件通常通过十六进制编辑,但我正在编写这个程序来帮助无法十六进制编辑的人):aÐP°À € ‚i‚c‚q ‚X‚X D T! ÿÿÿÿ
  • 被替换的位是“Д部分(我知道我正在用自己覆盖它,但在其他文件中它将是一个不同的值)
  • @Ricochet1136 如果它是二进制文件,则将其作为二进制文件打开并替换字节而不是字符。
  • 好主意,但我仍然需要弄清楚如何覆盖特定行上的特定位置

标签: python file character overwrite


【解决方案1】:

首先找到您要使用此更改的代码:

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)

【讨论】:

  • 那么对于 textToReplace,我是否只放置要替换的字符?
  • 正是 .. 和那个 fileToSearch 你的文件名
  • 我尝试了代码,但它似乎所做的只是完全清空文件。
【解决方案2】:

定义一个函数,参数为文件路径(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, "Ð")

【讨论】:

  • 代码有效,但它已经移动了所有字符,所以现在替换的文本已经从 CD-CE 移动到 C8-C9。这是因为 python 已将文件分解为与原来不同的部分。
  • 这里是股票文件:1drv.ms/u/s!AqRsP9xMA0g1iqMl-ZQbXUqX2WY8aA(这是一个onedrive文件)
  • @Ricochet1136 无法访问。
  • 不是默认的,因为它应该是这样的,但可以在记事本中查看(HxD也可以用于查看十六进制)
猜你喜欢
  • 2020-08-30
  • 2013-06-03
  • 2019-05-22
  • 1970-01-01
  • 2021-07-19
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多