File processing

Donn Cave donn at
Tue Jul 10 01:16:10 EDT 2001

Quoth Skip Montanaro <skip at>:
|     Chris> I'm trying to write a script that will open a file, delete the
|     Chris> first line, and then save the file with the same name.  Can
|     Chris> someone please point me in the right direction?  Thanks!
| Well, you've seen several Python examples and a Matlab example.  I usually
| use the shell for these sorts of quick-n-dirty file manipulations:
|     i=`wc -l <somefile`
|     i=`expr $i - 1`
|     tail -$i somefile > somefile.short
| Put that in a loop and you're all set:
|     for f in `whole buncha files` ; do
|         i=`wc -l <$f`
| 	i=`expr $i - 1`
| 	tail -$i $f > $f.tmp
| 	# cp -p $f $		# if you're paranoid
| 	mv $f.tmp $f
|     done

That's cool, but you might be interested to see if tail on
your platform supports a positive index (bet it does):

    for f in `whole buncha files`
        if tail +1 $f > $f.tmp
        then mv $f.tmp $f
        else rm $f.tmp

In the unlikely event it doesn't, sed '1d' is a safe bet.

	Donn Cave, donn at

More information about the Python-list mailing list