Opening 2 files and assigning them to 2 Sets in Python 3

Viewed 33

Here is my sample code. It works. But I am sure there is an easier way to store values in a set. I only know how to store them in a list first then transfer them into a set. The reason why I'm moving them into sets is to take advantage of the difference() method. Just asking the community for some advice. Everyone's input is well appeciated!

a_file = open(r'c:\a.csv', 'r')
b_file = open(r'c:\b.csv', 'r')

a_list = a_file.read().splitlines()
b_list = b_file.read().splitlines()

a_file.close()
b_file.close()

"""
Here, I am declaring 2 sets and then clear them of their 
values before storing the values from the lists.  
If I didn't do it this way, Python would think these were 
DICTIONARY datatypes instead and produce an syntax error.
"""

a_set = {1} #Just to get the program to recognize it as a set.
b_set.clear() #Then clear the data so that it is empty but stays as a set datatype.
a_set = {1}
b_set.clear()

a_set.update(a_list)
b_set.update(b_list)

difference_list = a_set.difference(b_set)
2 Answers

Just wrap a set() around the list.

def readfile(fn):
    with open(fn, 'r') as fh:
        return fh.read().splitlines()

diff = set(readfile("file1.txt")).difference(set(readfile("file2.txt")))

You can apply set to convert a list to a set on the spot. So this will be enough:

a_file = open(r'c:\a.csv', 'r')
b_file = open(r'c:\b.csv', 'r')

a_set = set(a_file.readlines())
b_set = set(b_file.readlines())

a_file.close()
b_file.close()

difference_list = a_set.difference(b_set)

But I would also recommend to apply with statement to perform basic file operations (open, close, etc) and ensure that in case of almost any exceptions they all will be closed properly. In that case the code will look like this:

with open(r'c:\a.csv', 'r') as a_file, open(r'c:\b.csv', 'r') as b_file:
    a_set = set(a_file.readlines())
    b_set = set(b_file.readlines())

difference_list = a_set.difference(b_set)
Related