'How do I change the only the first word of every line in a text file?
So I have actually worked out how to change the first word but the problem is its not just changing the first word only. So i have a file such as :
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
and i want to change it to:
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
So my code is:
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()
So what my code is doing is not only changing the first word but also any other instance of the number in the line. So something like this happens instead:
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
What am I doing wrong?
Solution 1:[1]
When you are calling replace()
it replaces every instance of that character in the string. Instead, just isolate the first character using [0]
so that it will only replace there. e.g:
this_file.write(line[0].replace(s,'2'))
EDIT: I see that someone commented the same thing as i was typing mine
Solution 2:[2]
try this
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()
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 | olijeffers0n |
Solution 2 |