'How to change first character in each line of a text file?
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
Solution 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
