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

How to change first char in each line in a TXT file

I want to change the first char 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

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

>Solution :

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)
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