Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (120 points)

 I have written a python function below which reads filenames from a file and return a tuple LIKE:

([filenames with no extensions], {'extension': [filename.extension]})

def file_extensions(filename):
        with_ext = []
        ext = []
        no_ext = []
        with open(filename, 'r') as f:
            for line in f:
                res = line.rstrip().rsplit('.',maxsplit=1)
                if len(res) == 1:
                    no_ext.append(res[0])
                else:
                    fulna = '.'.join(res)
                    ext.append(res[1])
                    with_ext.append(fulna)
            dicta = {k:[v] for k, v in zip(ext, with_ext)}
        return (no_ext, dicta)
    print(file_extensions('filenames.txt'))

The input file looks like:

file1.txt
mydocument.pdf
file2.txt
archive.tar.gz
test
The expected output should be:
(["test"], { "txt" : ["file1.txt", "file2.txt"], "pdf" : ["mydocument.pdf"], "gz" : ["archive.tar.gz"] } ) 

However, this code does not append the filenames with the same extensions. My function gives the following output:

(['test'], {'txt': ['file2.txt'], 'pdf': ['mydocument.pdf'], 'gz': ['archive.tar.gz']})

One can compare the outputs and can have the idea what is missing in my function.

Please log in or register to answer this question.

Related questions

Browse Categories

...