How do I compare two files and see if content is identical?

I am currently writing a code that asks a user if they want to either copy the contents of a file and put it into another file and also compare two contents of a file to see if they are identical. The copying part of my file works but not the part with comparing the contents of two files. I get an error saying:

line2=output_file.readlines()
io.UnsupportedOperation: not readable

This is my current code at the moment:

userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop')) #prompt user for comparing or copying
while userinput==1 or userinput==2:
    if userinput==1:
        with open(input('Enter file you want copied:')) as input_file:
            with open(input('Enter file you want contents copied to:'), 'w') as output_file:
                    for line in input_file:     #contents of first file copied to second file
                        output_file.write(line)
        userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))
    elif userinput==2:
        with open(input('Enter file you want to check')) as input_file:
            with open(input('Enter second file you want to check:'), 'w') as output_file:
                line1=input_file.readlines() #reads each line of the text
                line2=output_file.readlines()
                if line1==line2:        #checks if text is identical to each other
                    print('files are identical')
                    userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))
                elif line1 != line2:
                    print('This is where the file deviates')
                    print(line1)
                    print(line2)
                    userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))

What can I do to fix this?

2 answers

  • answered 2018-11-08 05:55 DYZ

    You opened the output file output_file for writing ('w'). You cannot read from it. Change 'w' to 'r'.

  • answered 2018-11-08 05:56 Neutrino

    You are trying to read the file but u open the file as write-able with the argument 'w'

    with open(input('Enter second file you want to check:'), 'w') as output_file:

    Either remove the argument or replace 'w' with 'r'

    with open(input('Enter second file you want to check:')) as output_file:

    OR

    with open(input('Enter second file you want to check:'), 'w') as output_file: