Search code examples
python-3.xiofwrite

Python file i/0: error -- How to write to a file when the filename given is a string?


I have a function that accepts d (dictionary that must be sorted asciibetically by key,) and filename (file that may or may not exist.) I have to have exact format written to this file and the function must return None.

Format: Every key-value pair of the dictionary should be output as: a string that starts with key, followed by ":", a tab, then the integers from the value list. Every integer should be followed by a "," and a tab except for the very last one, which should be followed by a newline.

The issue is when I go to close the file and run my testers, it tells me this error:

'str' object has no attribute 'close'

Obviously that means my file isn't a file, it's a string. How do I fix this?

Here is my current functions that work together to accept the dictionary, sort the dictionary, open/create file for writing, write the dictionary to the file in specified format that can be read as a string, and then close the file:

def format_item(key,value):
    return key+ ":\t"+",\t".join(str(x) for x in value)
def format_dict(d):
    return sorted(format_item(key,value) for key, value in d.items())
def store(d,filename):
    with open(filename, 'w') as f: 
        f.write("\n".join(format(dict(d))))
    filename.close()
    return None

Example of expected output:

IN: d = {'orange':[1,3],'apple':[2]}" OUT: store(d,"out.txt") the file contents should be read as this string: "apple:\t2\norange:\t1,\t3\n"


Solution

  • You have actually set the file handle to f but you are trying to close filename.

    so your close command should be f.close()