Nanor
Nanor

Reputation: 79

How to print strings in .txt file that is under a variable

So I'm asking the user to input two different .txt files to compare the strings inside. This is the return I want to get when the strings within the files are not the same is

No
String1
string2

I have everything working but I can't print the two strings inside each .txt file.

This is my code

print ('Enter the fist file name: ', end = '')
fileOne = input()

print ('Enter the fist file name: ', end = '')
fileTwo = input()

f1=open(fileOne,"r")
f2=open(fileTwo,"r")

if f1==f2:
    print('yes')
else:
    print('No')
    print(fileOne + fileTwo)

Upvotes: 0

Views: 41

Answers (2)

gilch
gilch

Reputation: 11681

There is a difference between the file objects and the strings you can read out of them. The file objects won't be equal even if they have the same contents. Not only are they different files, file objects don't compare equal even if they're pointing to the same file, only if they are the same object. If you want to read the whole file into memory, use .read(), like

f1 = open(fileOne).read()

Then f1 is a string, which you can compare equal by contents.

Best practice is to close files when you're done with them. Python can do this for you if you use the with statement:

with open(fileOne) as f1:
    f1 = f1.read()

Upvotes: 1

Hiadore
Hiadore

Reputation: 714

You need to read first after open to get the content.

print ('Enter the fist file name: ', end = '')
fileOne = input()

print ('Enter the fist file name: ', end = '')
fileTwo = input()

f1=open(fileOne,"r").readlines()
f2=open(fileTwo,"r").readlines()

if f1==f2:
    print('yes')
else:
    print('No')
    print(f1)
    print(f2)

Upvotes: 0

Related Questions