Re: python copy selected lines from one file to another using argparse or getopt

Dave Angel davea at davea.name
Wed Jan 8 18:57:22 EST 2014


On Wed, 8 Jan 2014 13:51:40 -0800 (PST), sagarnildass at gmail.com wrote:
> I am trying to write a program in python which searches for user 
specified words in a txt file and copies the selected lines 
containing that word into another file.

John Gordon has given you a good start on argument parsing.  So let's 
start with some general comments. 

Please indent by 4 columns.  Please factor your code into multiple 
functions so it's readable,  especially by you. Please learn that 
complementary conditions are best handled by else not by another if.

So the arguments to your main function should probably be two file 
objects and two lists. The function should call another one for each 
list, in a loop that looks something like

for line in infile:
    if check_include (includes, line and not check_exclude (excludes, 
line):
        dosomethingwith line

By the way checking the 2 filenames for equals doesn't begin to 
protect against trashing some file. Better to check if the output 
file exists, perhaps by opening in append mode and checking size.

-- 
DaveA




More information about the Python-list mailing list