Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace one column is txt file

I have several .txt files of annotation frame coordinates of objects in images.

The .txt file looks like below, the number of rows are not fixed and different for each .txt file.

2 0.063542 0.192593 0.021528 0.185185
2 0.106944 0.298148 0.030556 0.300000
2 0.186806 0.600000 0.061111 0.577778

Now I want to change the first column from 2 to 7 for in all these files, I’ve already tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for txtfile in txtfiles:

    with open(path + os.sep + txtfile, 'r') as file:
      filedata = file.read()
        
    # Replace the target string
    filedata2 = filedata.replace('2', '7')

However, ‘filedata’ here is a long string and all the ‘2’ will be replaced by ‘7’ (like 0.063542 becomes 0.063547). How can I replace only the first column?

>Solution :

Try:

'\n'.join(['7' + line[line.index(' '):] for line in file])

Code example:

data = """
2 0.063542 0.192593 0.021528 0.185185
2 0.106944 0.298148 0.030556 0.300000
2 0.186806 0.600000 0.061111 0.577778
"""

lines = '\n'.join(['7' + line[line.index(' '):] for line in data.strip().splitlines()])
print(lines)

Output:

7 0.063542 0.192593 0.021528 0.185185
7 0.106944 0.298148 0.030556 0.300000
7 0.186806 0.600000 0.061111 0.577778

File Example

I would suggest trying something like this – this will write to a file ending in .out rather than update the existing file, though this can be changed easily.

from os.path import join

for txtfile in txtfiles:
    with open(join(path, txtfile), 'r') as file:
        # Replace the target string
        new_lines = '\n'.join(['7' + line[line.index(' '):] for line in file])
        with open(join(path, txtfile + '.out'), 'w') as out_file:
            out_file.write(new_lines)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading