Home > OS >  Replace a string value from all the lines of all the text files in a directory
Replace a string value from all the lines of all the text files in a directory

Time:08-12

I have a several files with contents as such.

file01.txt

$ cat file01.txt
0 0.499594 0.154888 0.094968 0.156027
4 0.114448 0.101337 0.113636 0.035701
1 0.173701 0.154888 0.235390 0.068758
3 0.397727 0.669250 0.696429 0.063469

I want to replace the value of the first character with 0 in all the lines of all the files in a directory. What is the most pythonic way of doing it?

expected output

$ cat file01.txt
0 0.499594 0.154888 0.094968 0.156027
0 0.114448 0.101337 0.113636 0.035701
0 0.173701 0.154888 0.235390 0.068758
0 0.397727 0.669250 0.696429 0.063469

CodePudding user response:

$ipython
In [1]: import os
    ...:files = [f for f in os.listdir('.') if os.path.isfile(f)]
    ...:
In [2]: print(files)
['file01.txt', 'file02.txt', 'file03.txt', ... ]
In [3]: for f in files:
    ...:     # writing files to another directory called "new"
    ...:     with open('new/'  f, 'w') as fwrite, open(f) as fread:
    ...:         for line in fread:
    ...:             nline = '0'   line[1::]
    ...:             fwrite.write(nline)
    ...:

$ cat file01.txt
0 0.499594 0.154888 0.094968 0.156027
0 0.114448 0.101337 0.113636 0.035701
0 0.173701 0.154888 0.235390 0.068758
0 0.397727 0.669250 0.696429 0.063469

# similarly text in other files will also show the change.
  • Related