473,320 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

[perl-python] 20050126 find replace strings in file

© # -*- 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')
©
© for s in input:
© output.write(s.replace(stext,rtext))
© output.close()
© input.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: $!";
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: $!";
Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html

Jul 18 '05 #1
9 1826
OK. But please don't die throwing that string, or this post will lose
its educational purpose as it was meant to be.

Jul 18 '05 #2
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
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html


Jul 18 '05 #3

<ta*********@yahoo.com> wrote in message
news:11**********************@c13g2000cwb.googlegr oups.com...
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.
..........
Same for the close. Is there no way check a good close?


An exception (IOError) is raised when a file operation fails. The open()
and and close() statements should be enclosed in a try-except statement.

Please, take Xah Lee's postings with more than just a grain of salt. As a
matter of fact, you are better off ignoring them than trying to learn from
them. He is an egomaniac who is learning python and who thinks that he can
already teach others. Personally I doubt he will ever learn python well
enough to teach others. Just look at his English. He has a similar list
with a-word-a-day just like the perl-python a-lesson-a-day and he seems
indeed to know a lot of words. But his grammar is horrendous (there's a
word for you, Xah Lee!). And according to his own website he's been living
in North America for more than 15 years! English is a second language for
me too but you won't see me writing something like "this groups is for
Perlers who wants to learn Python".

It may be unfair to pick on his English, but it is the best way I can make
the point to someone who does not know python that Xah Lee does not know
what he's talking about. I find Xah Lee annoying and I could just ignore
him, but I am concerned that some people may actually take his statements
seriously and learn from them. I can't imagine why or how, but there are
actually 26 members in the perl-python Yahoo! group who have registered to
get these bogus lessons sent to them daily!

Dan
Jul 18 '05 #4
ta*********@yahoo.com wrote:
Xah Lee wrote:
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.


In this case, I'm pretty sure it's the user.

--Ala
Jul 18 '05 #5
Xah Lee wrote:
[...]
In perl, similar code can be achieved.
the following code illustrates.

if (scalar @ARGV != 4)
Why scalar()? The comparison already creates a scalar context, no need to
enforce it twice.
{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];
Ouch, how ugly. What's wrong with a simple
my ($one, $two, $three, $four) = @ARGV;

or the standard way using shift
for ($one, $two, $three, $four) {
$_ = shift;
}
open(F1, "<$infile") or die "Perl fucked up. Reason: $!";
open(F2, ">$outfile") or die "Perl fucked up. Reason: $!";
Really? Usually it's either the OS or the user (disk full, no write
permissions, wrong file name, ...)
while ($line = <F1>) {
Why $line? It doesn't serve any useful purpose here.
chomp($line);
Why chomp()? It doesn't serve any useful purpose here.
$line =~ s/$stext/$rtext/g;
If you would not have used $line above then you would not need the binding
here.
print F2 "$line\n";
If you would not have chomped the line above then you would not need to add
the newline back here. A simpler
print F2 $_;
would have sufficed
}
close(F1) or die "Perl fucked up. Reason: $!";
close(F2) or die "Perl fucked up. Reason: $!";


I find this highly unlikely. If at all then the OS failed to complete the
close.

jue
Jul 18 '05 #6
To follow up on Jurgen Exner's critique, I present Xah Lee's version, and
then my rewritten version.

"Xah Lee" <xa*@xahlee.org> writes:
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: $!";
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: $!";


#!/usr/bin/perl
use warnings;
use strict;

if (@ARGV != 4) {
die "Wrong arg! Unix BNF: $0 <sstr> <rstr> <file id1> <file id2>"
}
my ($stext, $rtext, $infile, $outfile) = @ARGV;

open my $infh, '<', $infile
or die "Error opening input file [$infile]: $!";
open my $outfh, '>', $outfile
or die "Error opening output file [$outfile]: $!";

while(<$infh>) {
s/$stext/$rtext/g;
print { $outfh } $_;
}
close($infh) or die "Error closing input file [$infile]: $!";
close($outfh) or die "Error closing output file [$outfile]: $!";

My version takes up more lines, but I don't count whitespace--
whitespace is not expensive, and when used properly adds greatly to
the readability of your program.

I've set followups to the only appropriate group for Mr. Lee's
postings.

-=Eric
--
Come to think of it, there are already a million monkeys on a million
typewriters, and Usenet is NOTHING like Shakespeare.
-- Blair Houghton.
Jul 18 '05 #7

[ Followup set ]
Dan Perl <da*****@rogers.com> wrote:
I can't imagine why or how, but there are
actually 26 members in the perl-python Yahoo! group who have registered to
get these bogus lessons sent to them daily!

There is one born every minute.
--
Tad McClellan SGML consulting
ta***@augustmail.com Perl programming
Fort Worth, Texas
Jul 18 '05 #8
On Wednesday 26 January 2005 7:13 pm, Tad McClellan wrote:
[ Followup set ]

Dan Perl <da*****@rogers.com> wrote:
I can't imagine why or how, but there are
actually 26 members in the perl-python Yahoo! group who have registered
to get these bogus lessons sent to them daily!


There is one born every minute.


Nah it is daily humor. Just think of it like a joke list. :)
Jul 18 '05 #9

kosh wrote:
Nah it is daily humor. Just think of it like a joke list. :)


Or a daily puzzler: how many blatantly stupid things can you find in 5
mins?

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Mark Wilson CPU | last post by:
This must be easy, but I'm missing something... I want to execute a Perl script, and capture ALL its output into a PHP variable. Here are my 2 files: -------------------------------------...
3
by: David F. Skoll | last post by:
Hi, I'm tearing my hair out on this one. I'm trying to embed a Perl interpreter into a C program. I need to be able to create and destroy the interpreter periodically, but will never actually...
1
by: Julia Bell | last post by:
I would like to run the same script on two different platforms. The directory in which the script(s) will be stored is common to the two platforms. (I see the same directory contents regardless...
6
by: surfivor | last post by:
I may be involved in a data migration project involving databases and creating XML feeds. Our site is PHP based, so I imagine the team might suggest PHP, but I had a look at the PHP documentation...
4
by: billb | last post by:
I installed a perl extension for PHP to use some perl inside my php primarily because I have perl working with oracle and not php and oracle. So I want to use my old perl scripts, and use the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.