I have been trying to replace a word in a text file with a value (say 1), but my outfile is blank.I am new to python (its only been a month since I have been learning it).
My file is relatively large, but I just want to replace a word with the value 1 for now. Here is a segment of what the file looks like:
JavaScript
x
28
28
1
NAME SECOND_1
2
3
ATOM 1 6 0 0 0 # ORB 1
4
5
ATOM 2 2 0 12/24 0 # ORB 2
6
7
ATOM 3 2 12/24 0 0 # ORB 2
8
9
ATOM 4 2 0 0 4/24 # ORB 3
10
11
ATOM 5 2 0 0 20/24 # ORB 3
12
13
ATOM 6 2 0 0 8/24 # ORB 3
14
15
ATOM 7 2 0 0 16/24 # ORB 3
16
17
ATOM 8 6 0 0 12/24 # ORB 1
18
19
ATOM 9 2 12/24 0 12/24 # ORB 2
20
21
ATOM 10 2 0 12/24 12/24 # ORB 2
22
23
#1
24
25
#2
26
27
#3
28
I want to first replace the word ATOM with the value 1. Next I want to replace #ORB with a space. Here is what I am trying thus far.
JavaScript
1
8
1
input = open('SECOND_orbitsJ22.txt','r')
2
output=open('SECOND_orbitsJ22_out.txt','w')
3
for line in input:
4
word=line.split(',')
5
if(word[0]=='ATOM'):
6
word[0]='1'
7
output.write(','.join(word))
8
Can anyone offer any suggestions or help? Thanks so much.
Advertisement
Answer
Use replace
.
JavaScript
1
2
1
line.replace("ATOM", "1").replace("# ORB", " ")
2
Untested code:
JavaScript
1
5
1
input = open('inp.txt', 'r')
2
output = open('out.txt', 'w')
3
clean = input.read().replace("ATOM", "1").replace("# ORB", " ")
4
output.write(clean)
5