Looping issues

anglozaxxon anglozaxxon at gmail.com
Thu Apr 5 15:43:27 EDT 2007


On Apr 5, 2:27 pm, Larry Bates <larry.ba... at websafe.com> wrote:
> brochu... at gmail.com wrote:
> > What I am trying to do is compare two files to each other.
>
> > If the 2nd file contains the same line the first file contains, I want
> > to print it. I wrote up the following code:
>
> > correct_settings = open("C:\Python25\Scripts\Output
> > \correct_settings.txt","r")
> > current_settings = open("C:\Python25\Scripts\Output\output.txt","r")
>
> > for line in correct_settings:
> >         for val in current_settings:
> >             if val == line:
> >                 print line + " found."
>
> > correct_settings.close()
> > current_settings.close()
>
> > For some reason this only looks at the first line of the
> > correct_settings.txt file. Any ideas as to how i can loop through each
> > line of the correct_settings file instead of just looking at the first?
>
> If the files aren't terribly large (not tested):
>
> correct_lines=open(r"C:\Python25\Scripts\Output" \
>                     "\correct_settings.txt", "r").readlines()
>
> current_lines=open(r"C:\Python25\Scripts\Output\output.txt",
>                     "r").readlines()
>
> for line in current_settings:
>     if line in correct_lines:
>         print line + " found"
>
> This does what you asked for but somehow I don't think it is
> what you want.  I would suggest that you take a look at difflib.
>
> Somththing along the lines of:
>
> import difflib
>
> correct_lines=open(r"C:\Python25\Scripts\Output" \
>                     "\correct_settings.txt", "r").readlines()
>
> current_lines=open(r"C:\Python25\Scripts\Output\output.txt",
>                     "r").readlines()
>
> delta=difflib.unified_diff(correct_lines, current_lines)
> diffs=''.join(delta)
>
> print diffs
>
> Will show you the lines that are different and some lines
> around it for context.
>
> -Larry

Sorry my solution didn't work.  The only other thing I can think of is
that something is screwy with the newlines, although this seems
silly.  I've heard Python has "universal newline" support, meaning \n
= \r = \r\n, etc.

Try printing the contents of the file in its entirety:
print current_settings.read()
And see if it prints the entire file, or just the first line.  I can't
imagine it won't print the whole thing.  Next, do print
current_settings.read().replace('\\','\\\\').  This will make the
escape characters visible, so you can see exactly what type of
newlines it's printing.  If the file is in Unix format and you're on
Windows, Python may be assuming the latter and not breaking lines
correctly.  Post what it prints.

Nick




More information about the Python-list mailing list