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:
NAME SECOND_1
ATOM 1 6 0 0 0 # ORB 1
ATOM 2 2 0 12/24 0 # ORB 2
ATOM 3 2 12/24 0 0 # ORB 2
ATOM 4 2 0 0 4/24 # ORB 3
ATOM 5 2 0 0 20/24 # ORB 3
ATOM 6 2 0 0 8/24 # ORB 3
ATOM 7 2 0 0 16/24 # ORB 3
ATOM 8 6 0 0 12/24 # ORB 1
ATOM 9 2 12/24 0 12/24 # ORB 2
ATOM 10 2 0 12/24 12/24 # ORB 2
#1
#2
#3
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.
input = open('SECOND_orbitsJ22.txt','r')
output=open('SECOND_orbitsJ22_out.txt','w')
for line in input:
word=line.split(',')
if(word[0]=='ATOM'):
word[0]='1'
output.write(','.join(word))
Can anyone offer any suggestions or help? Thanks so much.
The problem is that there's no comma after ATOM
in the input, so word[0]
doesn't equal ATOM
. You should be splitting on spaces, not commas.
You could also just use split()
without arguments.
Since you only do output.write
when a match is found, the output stays empty.
PS Try to use with
statements when opening files:
with open('SECOND_orbitsJ22.txt','r') as input,
open('SECOND_orbitsJ22_out.txt','w') as output:
...
Also, Alexander suggests the right tool for replacement: str.replace
. However, use it with caution as it's not position-aware. re.sub
is a more flexible alternative.
Use replace
.
line.replace("ATOM", "1").replace("# ORB", " ")
Untested code:
input = open('inp.txt', 'r')
output = open('out.txt', 'w')
clean = input.read().replace("ATOM", "1").replace("# ORB", " ")
output.write(clean)
Based on the file segment you've pasted here, you'll want to split each line on a space, rather than a comma. If there are no commas, line.split(',')
has no effect, and word[0]
is empty. Your output file is empty because you are never writing to it, as ATOM
will never be equal to the empty string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.