1

Is there a library/command in python to change a value in a specific location in a text file?

E.g. lets say I have a file called test.txt containing following data:

abc 123.2  45 text_data
ghk 12.43  123.45  89.3

The key thing is that this text file cannot be read as a structured data e.g. by using pandas or assuming that regular columns exist.

So, I have a separate file where I specify the row and columns which need to be changed to a new value.

row column_start  column_end new_value
2    5             9            10.4

Should replace 12.43 in the 2nd row with 10.4 in test.txt

2
  • If you can't assume any structure to the data, how do you have rows and columns. Are they just character positions? Commented Oct 12, 2015 at 21:09
  • Hi Jonah, that's right. those are character positions. thanks for clarifying Commented Oct 12, 2015 at 21:19

2 Answers 2

2

Once you have the line, extract the row, start,end and val then you can use fileinput.input to change the original file:

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)

That could replace more than just the value you want so slicing may be the safest approach:

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)

If you have multiple lines to change use a dict to create mappings:

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)
Sign up to request clarification or add additional context in comments.

1 Comment

No worries,you're welcome. you could also write to a tempfile using shutil to overwrite the original, it is covered in the last part of this answer stackoverflow.com/a/32801382/2141635
1

How about

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.