0

I want to change the first character on each line in the text file. Here is my code and my output but I don't know how to change and save that in the same text file.

for rf in glob.glob('./labels/train/*'):
    read=open(rf,'r')
    t=read.readlines()
    for ind in t:
        print(ind[0])

I have got what I want but I don't know how to change that and save it in the same text file.

1
1
1
1
1
4
3
  • Check This post Commented May 8, 2022 at 15:14
  • One more thing, What is the data inside side your old file. Commented May 8, 2022 at 15:17
  • 1 0.7141610738255033 0.7547281921618205 0.401006711409396 this is the data. I only want to change the first int. i want that first 1 to be zero on each line. Commented May 8, 2022 at 15:20

1 Answer 1

1

Try this:)

for rf in glob.glob('./labels/train/*'):
    read=open(rf,'r')
    t=read.readlines()

    read.close()
    for_write = [str(int(ind[0])-1)+ind[1:] for ind in t]   
    write = open(rf,'w')
    write.writelines(for_write)
    write.close()

or using with:)

for rf in glob.glob('./labels/train/*'):
    with open('test.txt','r')as read:
        t=read.readlines()
        for_write = [str(int(ind[0])-1)+ind[1:] for ind in t]
    with open('test.txt','w') as write:
        write.writelines(for_write)
Sign up to request clarification or add additional context in comments.

4 Comments

It does not change the values and deletes other values in txt file.
I want to change only the first char. others should be the same. i want to subtract 1 on every first int on each line.
@tornike you want 1 23423.34 23424 to 0 23423.34 23424 am I right or not.
yes. exactly. on each line. one more problem is that , these numbers in txt are string

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.