Search code examples
pythonfilepython-3.xattributeerror

Getting AttributeError Message when trying to close a file


I am using Python 3 to practice reading in files and using dictionaries. I am trying to close the file but am getting an error instead.

AttributeError: 'tuple' object has no attribute 'close'.

code:

try:
ifile = ("inputfile.txt", "r")
except IOError:
    print("Error opening file")
else:
    for line in ifile:
        line = line.strip()
        if not line or line[0] == "#":
            continue
        else:  
            data =line.split(" ") 
    mydict = {}

    for item in data:
        key = item[0] + item[-1]

        value = item[1:-1]
        mydict[key] = [value]
    print(mydict)
    ifile.close()

Why is this error happening and how can I fix it?


Solution

  • You haven't opened the file ! you have just created a tuple,change the following :

    ifile = ("inputfile.txt", "r")
    

    to :

    ifile = open("inputfile.txt", "r")