Question

I posted a question a while back:

Writing List To Text File

I was able to write a list of files from a dictionary into a text file.

So my code looks like this:

simonDuplicates = chain.from_iterable([files for files in file_dict.values() if len(files) > 1])

text_file.write("Duplicates Files:%s" % '\n'.join(simonDuplicates))

This basically prints out directories and files, for example:

C:/Users/Simon/Desktop/myfile.jpg

The problem is the forward slashes. I want them to be backslashes (as used in Windows). I tried using os.path.normpath but it doesn't work

simonDuplicates = chain.from_iterable([files for files in file_dict.values() if len(files) > 1])

os.path.normpath(simonDuplicates)

text_file.write("Duplicates Files:%s" % '\n'.join(simonDuplicates))

I get the following error:

Traceback (most recent call last):
  File "duff.py", line 125, in <module>
    os.path.normpath(duplicates)
  File "C:\Python27\lib\ntpath.py", line 402, in normpath
    path = path.replace("/", "\\")
AttributeError: 'itertools.chain' object has no attribute 'replace'

I think it doesn't work because I should be using iSlice?

Martijn Pieter's answer to this question looks about right:

Troubleshooting 'itertools.chain' object has no attribute '__getitem__'

Any suggestions?

Was it helpful?

Solution

You are trying to apply os.path.normpath on chain.from_iterable, which returns a generator object. So, you have to iterate till the generator exhausts, to get the complete list of filenames which are of type string.

You can use list comprehension like this

simonDuplicates = [os.path.normpath(path) for path in chain.from_iterable(files for files in file_dict.values() if len(files) > 1)]

Or you can use map function like this

simonDuplicates = map(os.path.normpath, chain.from_iterable(files for files in file_dict.values() if len(files) > 1))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top