You could do this by just modifying the first line of the file.
But here are some more general purpose utilities you could use (note it requires the re
module)
def read_xyz(
filename,
scale=1.):
""" Read xyz file
Params:
filename (str) - name of xyz file to read
Returns:
geom ((natoms,4) np.ndarray) - system geometry (atom symbol, x,y,z)
"""
lines = open(filename).readlines()
lines = lines[2:]
geom = []
for line in lines:
mobj = re.match(r'^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*$', line)
geom.append((
mobj.group(1),
scale*float(mobj.group(2)),
scale*float(mobj.group(3)),
scale*float(mobj.group(4)),
))
return geom
def write_xyz(
filename,
geom,
comment=0,
scale=1.0 #(1.0/units.ANGSTROM_TO_AU),
):
""" Writes xyz file with single frame
Params:
filename (str) - name of xyz file to write
geom ((natoms,4) np.ndarray) - system geometry (atom symbol, x,y,z)
"""
fh = open(filename,'w')
fh.write('%d\n' % len(geom))
fh.write('{}\n'.format(comment))
for atom in geom:
fh.write('%-2s %14.6f %14.6f %14.6f\n' % (
atom[0],
scale*atom[1],
scale*atom[2],
scale*atom[3],
))
If you read the file and then write the file it will automatically save it with the correct number of atoms.
nlines=`wc -l test.xyz | awk '{print $1}'`; natoms=$((nlines-2)); sed -i "1s/.*/$natoms/" test.xyz
$\endgroup$