【问题标题】:change a value in a specific location in a text file in python更改python文本文件中特定位置的值
【发布时间】:2015-10-12 21:00:46
【问题描述】:

python 中是否有库/命令可以更改文本文件中特定位置的值?

例如假设我有一个名为 test.txt 的文件,其中包含以下数据:

abc 123.2  45 text_data
ghk 12.43  123.45  89.3

关键是这个文本文件不能作为结构化数据读取,例如通过使用 pandas 或假设存在常规列。

所以,我有一个单独的文件,我在其中指定需要更改为新值的行和列。

row column_start  column_end new_value
2    5             9            10.4

应该将第二行中的 12.43 替换为 test.txt 中的 10.4

【问题讨论】:

  • 如果你不能对数据假设任何结构,你怎么会有行和列。它们只是角色位置吗?
  • 嗨,乔纳,没错。这些是字符位置。感谢澄清

标签: python


【解决方案1】:

一旦你有了行,提取行、开始、结束和 val 然后你可以使用fileinput.input 来更改原始文件:

from fileinput import input
from sys import stdout

line = "2    5             9            10.4"

r, st, ed, val = line.split()
r, st, ed = int(r), int(st), int(ed)
for ind, line in enumerate(input("test.txt",inplace=True), 1):
    if ind == r:
        stdout.write(line.replace(line[st-1:ed], val))
    else:
        stdout.write(line)

这不仅可以替换您想要的值,因此切片可能是最安全的方法:

for ind, line in enumerate(input("test.txt", inplace=True), 1):
    if ind == r:
        new = line[:st-1] + val + line[ed:]
        stdout.write(new)
    else:
        stdout.write(line)

如果您要更改多行,请使用 dict 创建映射:

from fileinput import input
from sys import stdout

with open("changes.txt") as f:
    next(f)
    data = {int(r): {"st": int(st), "ed": int(ed), "val": val} for r, st, ed, val in map(str.split, f)}
    for ind, line in enumerate(input("test.txt"), 1):
        if ind in data:
            d = data[ind]
            new = line[:d["st"] - 1] + d["val"] + line[d["ed"]:]
            stdout.write(new)
        else:
            stdout.write(line)

【讨论】:

【解决方案2】:

怎么样

import sys
# load the values from the instruction file however you want (a separate problem)
row=2
column_start=5
column_end=9
new_value=10.4

# process the data
for line_num, contents in enumerate(open("test.txt")):
    if line_num == row - 1:
        contents = contents[:column_start-1] + str(new_value) + contents[column_end:]
    # write the results somewhere
    sys.stdout.write(contents)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多