如何更改文本文件每一行的第一个字符?
How to change first character in each line of a text file?
我想更改文本文件中每一行的第一个字符。这是我的代码和我的输出,但我不知道如何更改并将其保存在同一个文本文件中。
for rf in glob.glob('./labels/train/*'):
read=open(rf,'r')
t=read.readlines()
for ind in t:
print(ind[0])
我已经得到了我想要的东西,但我不知道如何更改它并将它保存在同一个文本文件中。
1
1
1
1
1
4
试试这个:)
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()
或使用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)
我想更改文本文件中每一行的第一个字符。这是我的代码和我的输出,但我不知道如何更改并将其保存在同一个文本文件中。
for rf in glob.glob('./labels/train/*'):
read=open(rf,'r')
t=read.readlines()
for ind in t:
print(ind[0])
我已经得到了我想要的东西,但我不知道如何更改它并将它保存在同一个文本文件中。
1
1
1
1
1
4
试试这个:)
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()
或使用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)