Loading...
Loading...

Reputation: 1

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?

Upvotes: 0

Views: 110

Answers (2)

Neutrino
Neutrino

Reputation: 363

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:

Upvotes: 1

DYZ
DYZ

Reputation: 57033

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

Upvotes: 0

Related Questions