0

I am a beginner in Python and have a problem. I have a *.dat file and a number has to be changed using python. There is a number in line 5164 "6.88662e+10" which has to be replaced with the number "1". It looks like this when opened from UltraEdit https://i.stack.imgur.com/GnMnk.jpg

How can it be done?

devinxxxd
  • 63
  • 2
  • 10
  • 2
    File read and write, and simple numerical assignment are all covered quite well in tutorials and examples. Where are you stuck? Please repeat [how to ask](https://stackoverflow.com/help/how-to-ask) from the intro tour. – Prune Apr 12 '20 at 04:05

2 Answers2

1

You'll have to give the path either relative to the current working directory

path/to/file.dat

Or you can use the absolute path to the file

C:user/dir/path/to/file.dat

Read the data,replace the values and then write it

# Read in the file
with open('file.dat', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('6.88662e+10', '1')

# Write the file out again
with open('file.dat', 'w') as file:
  file.write(filedata)
AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35
  • Can this replace command be used only for line 5164? because there might be the same value in other lines too which we don't wanna replace – devinxxxd Apr 12 '20 at 06:32
  • You can do this `filedata.replace('6.88662e+10', '1',1)` this will only replace it once – AzyCrw4282 Apr 12 '20 at 06:34
  • But that's assuming that the value of occurrence happens on line 5164 first. See [here](https://www.w3schools.com/python/ref_string_replace.asp) for more on the replace method – AzyCrw4282 Apr 12 '20 at 06:34
  • There are other places also where this number is set but only the 5164 line has to be edited. Any other ways? – devinxxxd Apr 12 '20 at 06:47
  • Are the positions that the number occurs greater or less than 5164? If they are all greater than 5164 then this should work fine. Otherwise, this will not work and you would have to use the other answer. – AzyCrw4282 Apr 12 '20 at 06:49
0

This solution doesn't require loading all the file contents into memory:

import os

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

os.rename('out.dat', 'in.dat')
jubnzv
  • 1,526
  • 2
  • 8
  • 20
  • This doesn't replace the original file. It gave an error."FileExistsError: [WinError 183] Cannot create a file when that file already exists" – devinxxxd Apr 12 '20 at 07:13
  • 1
    @devinxxxd this is a windows-specific behavior. The following question can help you: https://stackoverflow.com/questions/8107352/force-overwrite-in-os-rename – jubnzv Apr 12 '20 at 07:21