But how come if you call the function junk again after the program finished executing and showed the output, it will return two empty dicts?
Because the code is also poorly designed, ideally you should send the file name to the function, open the file there, read and close it.
You can fix your code this way ...
def junk(fh):
d1 = {}
d2 = {}
for line in fh:
columns = line.split(",")
letters = columns[0]
numbers = columns[1]
d1[letters] = numbers
d2[numbers] = letters
return d1, d2
def something(d1, d2):
print d1
print d2
if __name__ == "__main__":
fh = open("filename.txt")
d1, d2 = junk(fh)
something(d1, d2)
print( '-'*50 )
# second time around
# file handle fh is at the end of the file now
# reset it to the start of the file
fh.seek(0)
d1, d2 = junk(fh)
something(d1, d2)
"""my output -->
{'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
{'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
--------------------------------------------------
{'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
{'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
"""
This would have been the better design ...
"""assume file "filename.txt" has this content
a,1
b,2
c,3
d,4
"""
def file2dictionary(fname):
"""
read data from file and create a dictionary d1 and its reverse d2
"""
fh = open("filename.txt")
d1 = {}
d2 = {}
for line in fh:
columns = line.split(",")
letters = columns[0]
numbers = columns[1]
d1[letters] = numbers
d2[numbers] = letters
fh.close()
return d1, d2
def print_dict(d1, d2):
"""print the two dictionaries d1 and d2"""
print(d1)
print(d2)
if __name__ == "__main__":
fname = "filename.txt"
d1, d2 = file2dictionary(fname)
print_dict(d1, d2)
print( '-'*50 )
# test second time around
d1, d2 = file2dictionary(fname)
print_dict(d1, d2)
"""my output -->
{'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
{'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
--------------------------------------------------
{'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
{'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
"""
Note:
If you use the
print() function instead of the
print statement this code will work with Python2 and Python3.