Screwing Up looping in Generator

Steve D'Aprano steve+python at pearwood.info
Wed Jan 4 04:41:53 EST 2017


On Wed, 4 Jan 2017 01:09 pm, Sayth Renshaw wrote:

> Untested as i wrote this in notepad at work but, if i first use the
> generator to create a set of filenames and then iterate it then call the
> generator anew to process file may work?

It "may" work. Or it "may not" work. It is hard to tell because we don't
have enough context to understand your code.

Let me see if I can guess what you are doing:

> Good idea or better available?
> 
> def get_list_of_names(generator_arg):
>     name_set = set()
>     for name in generator_arg:
>         base = os.path.basename(name.name)
>         filename = os.path.splitext(base)[0]
>         name_set.add(filename)
>     return name_set

What does "generator_arg" do? Since you iterate over it, it could be a list,
a tuple, any other sequence, or an iterator. Why does it have to be a
generator?

What is "name.name"?

I *think* that your intention is to take a list of objects that hold
filenames:


["C://My Documents/data.txt", "C://My Documents/folder/image.jpg",
 "C://file.txt", "D://installer.exe", "E://folder/image.gif"]

strip off the path, strip off the file extensions, remove any duplicates,
giving:

set(["data", "image", "file", "installer"])

(Notice that image.jpg and image.gif count as duplicates.)


If that is what you want, then I think get_list_of_names will work, except:

- the name is WRONG: it returns a set, not a list;

- the name does not describe what the function does;

- there's no documentation

- the name of the argument is misleading, it doesn't have to be a generator.


Other than that, I think the code does what I think you want.


>  for file_name in name_set:
>      directory = "output"
>          with open(os.path.join(directory, filename, 'w', newline='') as
>          csvf:
>             for file in rootobs:
>               # create and write csv


Your indentation is wrong.

What's "rootobs"?

The code you show here does not have enough detail for me to even try to
guess what it does. 





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list