0

I am trying to replace some of the first characters in lines from multiple txt files and have this code but the output is wrong:

for filename in glob.glob('./labels/**/*.txt', recursive=True):
with open(filename, 'r') as f:
    original_lines = f.readlines()
with open(filename, 'w') as out:
    for line in original_lines:
        if line.startswith('0'):
            line0 = line
            out.write(line0)
        if line.startswith('1'):
            line1 = line
            out.write(line1)
        if line.startswith('2'):
            line2 = line
            out.write(line2)
        if line.startswith('3'):
            line3 = line
            out.write(line3)
        if line.startswith('5'):
            line4 = '4' + line[1:]
            out.write(line4)
        if line.startswith('7'):
            line5 = '5' + line[1:]
            out.write(line5)
        if line.startswith('9'):
            line6 = '6' + line[1:]
            out.write(line6)
        if line.startswith('10'):
            line7 = '7' + line[1:]
            out.write(line7)
        if line.startswith('11'):
            line8 = '8' + line[1:]
            out.write(line8)
        if line.startswith('12'):
            line9 = '9' + line[1:]
            out.write(line9)

So if I have a file like this:

0 0.2 0.4 0.8

12 0.1 0.1 0.25

7 0.66 0.80 0.91

I want output to be:

0 0.2 0.4 0.8

9 0.1 0.1 0.25

5 0.66 0.80 0.91

2
  • 2
    If a line starts with '12' both .startswith('1') and .startswith('12') will be true which could explain part of your issues. Commented Mar 15, 2021 at 17:32
  • Yes, that was one of the problems,I solved it by using line.split(' '), thank you. Commented Mar 15, 2021 at 18:04

1 Answer 1

1

I think you have some slicing issues for example lets say your input is 12 0.1 0.1 0.25 line[1:] is going to be 2 0.1 0.1 0.25 because your input is a string. You can use something like:

line = '12 0.1 0.1 0.25'.split(' ') #convert your string to a list

temp = int(line[0]) #get first element and convert to integer to make comparisons easier

if temp < 3:
    print(' '.join(line))
elif temp == 5: 
    line[0] = '4'
    print(' '.join(line))
elif temp == 7:
    line[0] = '5'
    print(' '.join(line))
elif temp > 8:
    line[0] =str(temp - 3)
    print(' '.join(line))

#Output: 

9 0.1 0.1 0.25

Note: It's better to use elif instead of if in your case because if one of your conditions are true it is not going to check rest of the conditions. More info here

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

1 Comment

Thank you, as soon as I posted I saw that it would slice bad and I solved it using line.split(' ')

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.