20050126 find replace strings in file

takarov2003 at yahoo.com takarov2003 at yahoo.com
Wed Jan 26 17:00:36 EST 2005


Xah Lee wrote:
> © # -*- coding: utf-8 -*-
> © # Python
> ©
> © import sys
> ©
> © nn = len(sys.argv)
> ©
> © if not nn==5:
> ©     print "error: %s search_text replace_text in_file out_file" %
> sys.argv[0]
> © else:
> ©     stext = sys.argv[1]
> ©     rtext = sys.argv[2]
> ©     input = open(sys.argv[3])
> ©     output = open(sys.argv[4],'w')

I guess there is no way to check if the file opened fine?  What if the
filesystem or file is locked for this user/session.  Pretty puny
language if it cannot tell you that it cannot do what you tell it to.
> ©
> ©     for s in input:
> ©         output.write(s.replace(stext,rtext))
> ©     output.close()
> ©     input.close()

Same for the close.  Is there no way check a good close?


>
> -------------------------
> save this code as find_replace.py
> run it like this:
> python find_replace.py findtext replacetext in_file out_file
>
> the sys.argv is from sys. sys.argv[0] is the program's name itself.
>
> note the idiom
> "for variable_name in file_object"
>
> note that since this code reads each
> line in turn, so huge file is of no-problemo
>
> the code is based from Python
> Cookbook of Alex Martelli & David
> Ascher, page 121
>
> in Python terminal, type help() then
> 'FILES' and or 'sys'
> for reference.
>
> try to modify this file for your
> needs.
> --------------------------------------
> In perl, similar code can be achieved.
> the following code illustrates.
>
> if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 <sstr> <rstr>
> <file id1> <file id2>\n"}
> $stext=$ARGV[0];
> $rtext=$ARGV[1];
> $infile = $ARGV[2];
> $outfile = $ARGV[3];
> open(F1, "<$infile") or die "Perl fucked up. Reason: $!";
> open(F2, ">$outfile") or die "Perl fucked up. Reason: $!";

In 7 years of perl programming, I have never seen an open error that
had anything to do with perl processing.  Normally, if I get an error,
the file does not exist, or has permissions set so that the current
user/session is not allowed to open the file.

> while ($line = <F1>) {
> chomp($line);
> $line =~ s/$stext/$rtext/g;
> print F2 "$line\n";
> }
> close(F1) or die "Perl fucked up. Reason: $!";
> close(F2) or die "Perl fucked up. Reason: $!";

Same here.  Never seen Perl fuck up on closing a file.  Usually
something in the OS or file system that does it.
> Xah
>  xah at xahlee.org
>  http://xahlee.org/PageTwo_dir/more.html




More information about the Python-list mailing list