[英]How do I change the only the first word of every line in a text file?
所以我实际上已经想出了如何改变第一个词,但问题是它不仅仅是改变第一个词。 所以我有一个文件,例如:
2 0.268278 0.356394 0.027123 0.044025
4 0.241745 0.528302 0.035377 0.035639
4 0.257075 0.491614 0.037736 0.033543
5 0.275354 0.307128 0.060142 0.062893
0 0.283019 0.551363 0.115566 0.572327
0 0.043042 0.292453 0.076651 0.159329
我想将其更改为:
3 0.268278 0.356394 0.027123 0.044025
5 0.241745 0.528302 0.035377 0.035639
5 0.257075 0.491614 0.037736 0.033543
9 0.275354 0.307128 0.060142 0.062893
0 0.283019 0.551363 0.115566 0.572327
0 0.043042 0.292453 0.076651 0.159329
所以我的代码是:
source = 'C:/Users/asmita.nandi/Downloads/Kitchen_black&white/Annotations1'
for root, dirs, filenames in os.walk(source):
for f in filenames:
this_file = open(os.path.join(source, f), "r")
this_files_data = this_file.readlines()
this_file.close()
# opens all txt file in directory
this_file = open(os.path.join(source, f), "w")
for line in this_files_data:
s=line[0]
if line[0] in "1" :
this_file.write(line.replace(s,'2'))
if line[0] in "2" :
this_file.write(line.replace(s,'3'))
if line[0] in "0":
this_file.write(line)
if line[0] in "3":
this_file.write(line.replace(s,'4'))
if line[0] in "4":
this_file.write(line.replace(s,'5'))
if line[0] in "5":
this_file.write(line.replace(s,'9'))
this_file.close()
因此,我的代码所做的不仅是更改第一个单词,而且还更改该行中数字的任何其他实例。 所以这样的事情会发生:
3 0.359080 0.359539 0.037133 0.060797
9 0.369104 0.289119 0.070799 0.079472
9 0.678696 0.143606 0.099429 0.090147
5 0.307193 0.590157 0.038915 0.052511
0 0.392099 0.620545 0.173349 0.746331
0 0.653892 0.479036 0.135613 0.752621
我究竟做错了什么?
当您调用replace()
时,它会替换字符串中该字符的每个实例。 相反,只需使用[0]
隔离第一个字符,以便它只会替换那里。 例如:
this_file.write(line[0].replace(s,'2'))
编辑:我看到有人评论了与我输入我的相同的内容
试试这个
import os
os.chdir(r" **write Folder Path here** ")
for paths,folders,files in os.walk(os.getcwd()):
for file in files:
if file.endswith("txt"):
reading_file = open(file,"r")
new_str = ""
for line in reading_file:
new_line=(line[0].replace(line[0],'0')+line[1:])
new_str += new_line
writing_file = open(file,"w")
writing_file.write(new_str)
writing_file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.