Issue
I have a input data in a file input.txt. I want to add 200 with each row of 4th column and want to append just beside to it in the format same as original.
Input.txt
> > >
0.000 5.064 -0.15835E-01 -7.755619582136471027e-03
0.700 9.064 -0.21715E-02 -1.302134466433525067e-02
0.800 5.064 0.18954E-01 -1.691809184964498253e-02
> > >
0.500 4.977 0.32899E-02 1.439701445411046415e-02
0.200 6.977 0.15972E-01 6.094966468334198084e-03
0.700 4.977 0.30631E-01 -5.640445453166963163e-03
out.txt
> > >
0.000 5.064 -0.15835E-01 -7.755619582136471027e-03 199.99224438041787
0.700 9.064 -0.21715E-02 -1.302134466433525067e-02 199.98697865533566
0.800 5.064 0.18954E-01 -1.691809184964498253e-02 199.98308190815035
> > >
0.500 4.977 0.32899E-02 1.439701445411046415e-02 200.01439701445412
0.200 6.977 0.15972E-01 6.094966468334198084e-03 200.00609496646834
0.700 4.977 0.30631E-01 -5.640445453166963163e-03 199.99435955454683
I tried :
import numpy as np
data=np.loadtxt('input.txt')
data1=data(:,3)+200
I am getting error ValueError: could not convert string to float: '>'
I hope some expert will help me overcoming this problem.
Solution
You have non-numeric symbols in the file. You can treat them as comments:
data = np.loadtxt('input.txt', comments=">")
But then you will not be able to preserve them in the output file. I am afraid your only option is to read the file line by line in a loop:
CHANGE = 200
with open('input.txt') as infile, open('out.txt', 'w') as outfile:
for line in infile:
if not line.startswith('>'): # Needs a modification
parts = line.split()
parts.append(str(float(parts[3]) + CHANGE) + '\n')
line = ' '.join(parts)
outfile.write(line)
Answered By - DYZ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.