0

I have 500 *.txt files which are of the form given below

1 0.211648 0.496528 0.230114 0.159722
11 0.549716 0.232639 0.082386 0.145833
5 0.687500 0.539931 0.130682 0.128472
1 0.534091 0.809028 0.221591 0.194444
2 0.127841 0.637153 0.119318 0.128472
2 0.579545 0.482639 0.090909 0.069444
1 0.657670 0.269097 0.105114 0.121528
2 0.737216 0.348958 0.025568 0.086806
2 0.484375 0.302083 0.031250 0.069444

I need to replace '11' 1st number in the row with '10' I have written following program for it but it doesn't work. can you please help.

import numpy as np
import glob
import os

os.chdir(r'../images')
myFiles = glob.glob('image*.txt')
import numpy as np
for i1 in myFiles:

  # print(i1)
  with open(i1, 'r') as f:
    # read a list of lines into data
    lines = f.readlines()

  r_id = np.arange(len(lines))
  for i in r_id:
      idx = list(map(float, lines[i].split(' ')))
      idx[0]=int(idx[0])
      if(idx[0]==11): 
        idx[0]=10
        with open(i1, 'w') as f:
          f.writelines(lines)

  f.close()
2
  • 1
    perhaps you meant myFiles = glob.glob('image\*.txt')? Commented May 28, 2021 at 16:46
  • @Sujay I checked by printing the file names Commented May 28, 2021 at 16:56

1 Answer 1

2

You're trying to use integers (10 and 11), but what you have there are strings. You don't need numpy for this, it's a simple text substitution:

import glob
import os

os.chdir('../images')
myFiles = glob.glob('image*.txt')
for i1 in myFiles:
    lines = open(il,'r').readlines()
    with open(il,'w') as fout:
        for line in lines:
            if line.startswith('11 '):
                line = '10 '+line[3:]
            print( line, file=fout, end='' )

It could be even simpler if you wanted to write the result to a temp file and rename afterward. Then you wouldn't need to read the whole file in.

Sign up to request clarification or add additional context in comments.

2 Comments

your code creates spaces between lines, can you please tell me how to fix that
Honestly, you should have been able to figure that out. It has spaces because "readlines" leaves the newline at the end, and print adds another. So, you can either .strip() the newline, or tell print not to add one, which is what I did here.

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.