> I'm just trying to create a new file for all
> the lines that startswith my string. So if my original
> file looks like this:
> 
> 1 Line 1
> 1 Line 2
> 2 Line 1
> 2 Line 2
> 3 Line 1
> 4 Line 1
> 
> I want to read in all the ones starting with 1 and
> then save them to a new file. I can get the result I
> want there by using :
> If line.startswith('1'):
>            
> But can't figure out how to save these lines to
> another file.

Something like this, perhaps?

"""
def filter_file(in_fn, out_fn, to_match):
    fin = open(in_fn, "r")
    fout = open(out_fn, "w")
    for line in fin:
        if line.startswith(to_match):
            fout.write(line)
    fin.close()
    fout.close()
"""

Or, to be concise (but less clear):

"""
def filter_file(in_fn, out_fn, to_match):
    open(out_fn, "w").write("".join([line for line in open(in_fn, "r") if
line.startswith(to_match)]))
"""

(That's all one line).

=Tony.Meyer

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to