devinxxd
devinxxd

Reputation: 5

Editing a specific part of specific line of *.dat file in Python

The line 5163 is 10,0.3. This code written below edits the whole line to 5,0.3. I want to just replace number 10 to 5 without replacing the whole line. I want to edit that specific part. How can this be done?

import os
import time

with open('Job-1.dat', 'rt') as fin:
    with open('out.dat', 'wt') as fout:
        for i, line in enumerate(fin):
            if i == 5163:
                fout.write(' 5, 0.3\n')
            else:
                fout.write(line)

os.remove('Job-1.dat')
time.sleep(5)
os.rename('out.inp', 'Job-1.inp')

Upvotes: 0

Views: 297

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51643

You can keep the last part of the line by replacing only what you want to replace:

# your code
        for i, line in enumerate(fin):
            if i == 5163:
                modified = line.replace("10,", "5,")
                fout.write(modified + '\n')
            else:
                fout.write(line)

# etc

See str.replace.

As @Blotosmetek mentioned, adding a '\n' to each line (wich already contains one at the end) will lead to empty lines in your output file - in case thats not wanted, use

    fout.write(modified) # no extra '\n' added

Upvotes: 1

Błotosmętek
Błotosmętek

Reputation: 12927

Change:

        if i == 5163:
            fout.write(' 5, 0.3\n')

to:

        if i == 5163:
            items = line.split(',')
            out = ','.join(['10'] + items[1:])
            fout.write(out)

Upvotes: 2

Related Questions