I'm really new to programming (really, really new) and need help with the basics. I'm trying to write a program with python that will compare the contents of two .txt files, one a reference and the other the source. The contents are a simple random listing of names, and I want it to print out if there are any names in the source that are not in the reference.
I've looked at other stuff on this site but every time I tried it, the terminal would never actually give a result, even if there was a print command in the program.
I also have a hard time reading the language of a program and ascertaining it's exact function, so something with clear directions would be really appreciated.
As far as I have is:
ref = open("reference.txt")
sor = open("source.txt")
list1 = ref.read()
list2 = sor.read()
for i in list2:
if i != list:
print i
ref.close()
sor.close()
And when I try and run this, it says "expected an indented block"? at the 'print i' line. Why?
Please help me out, as I have to teach myself this stuff and am not doing too well.
Thanks.
If you are totally, completely new to programming then it will take you some time to be able to implement what you describe. Take a step back, pour yourself a beverage, and start here. Start at the beginning, and repeat each illustration until you understand.
http://docs.python.org/tutorial/
As previously mentioned, your inner if statement needs to be indented, as
for i in list2:
if i != list:
print i
This requires two indents because it is two nested blocks. As a basic rule of thumb, anywhere you're ending a line with a colon (:), you're starting a new code block, and should be indenting another level. This is so you can un-indent once to end the if block without ending the for block.
However, I doubt this will do what you want based on your description. It's likely you wanted something more like
sourceLines = set(sor.readLines())
for line in ref.readlines():
if line not in sourcelines:
print line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With