I am using the script below to extract data from some trajectory file and dump the data into new files files. I can use directive “>” to redirect results into a file but I need to do like this for more then 2000 files then. For make things easy I tried to open a file and let the python itself direct the results into a file.
To achieve that I added a line, at the place, (##) in the code, to open a file as shown below.
Also I added a line to direct the results into a file as shown in the code below at line contains (###).
#!/usr/bin/env python
'''
always put -- #!/usr/bin/env python -- at the shebang
'''
from Scientific.IO.NetCDF import NetCDFFile as Dataset
import itertools as itx
inputfile = "../traj-waters/waters1445-MD001-run1000.traj"
for FRAMES in range(0,2):
frame = FRAMES
text_file = open("velo-Output.dat", "w") (##)
#inputfile = 'mdcrd'
ppp = inputfile
def grouper(n, iterable, fillvalue=None):
args = [iter(iterable)] * n
return itx.izip_longest(fillvalue=fillvalue, *args)
formatxyz = "%12.7f%12.7f%12.7f%12.7f%12.7f%12.7f"
formatxyz_size = 6
formatxyzshort = "%12.7f%12.7f%12.7f"
formatxyzshort_size = 3
#ncfile = Dataset(inpitfile, 'r')
ncfile = Dataset(ppp, 'r')
variableNames = ncfile.variables.keys()
#print variableNames
shape = ncfile.variables['coordinates'].shape
'''
do the header
'''
print 'title ' + str(frame)
print "%5i%15.7e" % (shape[1],ncfile.variables['time'][frame])
'''
do the velocities
'''
try:
xyz = ncfile.variables['velocities'][frame]
temp = grouper(2, xyz, "")
for i in temp:
z = tuple(itx.chain(*i))
if (len(z) == formatxyz_size):
print formatxyz % z
text_file.write('formatxyz\n' % z)) (###)
elif (len(z) == formatxyzshort_size): print formatxyzshort % z
except(KeyError):
xyz = [0] * shape[2]
xyz = [xyz] * shape[1]
temp = grouper(2, xyz, "")
for i in temp:
z = tuple(itx.chain(*i))
if (len(z) == formatxyz_size): print formatxyz % z
elif (len(z) == formatxyzshort_size): print formatxyzshort % z
x = ncfile.variables['cell_angles'][frame]
y = ncfile.variables['cell_lengths'][frame]
text_file.close()
But I get error if I run this code as below.
Traceback (most recent call last):
File "./Nctorst-onlyVelo.py", line 73, in <module>
text_file.write(str('formatxyz\n' % z))
TypeError: not all arguments converted during string formatting
Since I am newbie into python I find lost to correct this issue.
Advance thanks for help.
Regards
Either you made a Typo, or did not understand how string formating with replacement operator works
The Line
Should be written similar to the previous line
Also you should look forward to use the Format String Syntax