Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 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 to answer this question.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 24, 2021 in Python by laddulakshana (16.4k points)
0 votes
2 answers
asked Aug 23, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...