TypeError: coercing to Unicode: need string or buffer, list found: how to create a loop
<p>I'm working on a python script that will add a folder and all of its contents to a zip file using both <code>zipfile</code> and <code>os</code>.</p>

<pre><code>z = ZipFile("mynewfile.zip", "w")
z.write(os.walk(directory))
z.printdir()
z.close()
</code></pre>

<p>Unfortunatly I've found that this is considered a list when using <code>os.walk</code>, which causes the error:</p>

<pre><code>TypeError: coercing to Unicode: need string or buffer, list found: how to create a loop
</code></pre>

<p>Looking around at this error, I think I need a loop to cycle through each item in the list. My problem is that I can't figure out how to translate previous answers for my specific needs. 
e.g <a href="http://stackoverflow.com/questions/21580270/typeerror-coercing-to-unicode-need-string-or-buffer-list-found">TypeError: coercing to Unicode: need string or buffer, list found</a></p>

<p>I have also tried </p>

<pre><code>for root dirs files in os.walk(directory)
    z.write(files)
</code></pre>

<p>which also causes the same error to occur.</p>

<p>However using</p>

<pre><code>for root dirs files in os.walk(directory)
    z.write(root)
</code></pre>

<p>displays all the folders within the directory, but no files. I'm not sure why this does not count as a list.</p>

<p>I assume I need to somehow combine these 2 ideas, any help doing so would be greatly appeciated.</p>

<p>The following code should do it. Since files is a list. You simply iterate over that list and write the filenames to the zipfile. In the code below I'm also using the context manager <code>with</code> with that I don't need to close the file manually, because it does that for me. </p>

<pre><code>from zipfile import Zipfile

for root, dirs, files in os.walk(directory):
    for f in files:
        with Zipfile('new_zip.zip', 'w') as z:
            z.write(f)
</code></pre>

python