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
martineau
  • 119,623
  • 25
  • 170
  • 301
tornike
  • 15
  • 5
  • Check This [`post`](https://stackoverflow.com/questions/72162145/how-do-i-edit-a-txt-file-in-python/72162177#72162177) – codester_09 May 08 '22 at 15:14
  • One more thing, What is the data inside side your old file. – codester_09 May 08 '22 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. – tornike May 08 '22 at 15:20

1 Answers1

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)
codester_09
  • 5,622
  • 2
  • 5
  • 27