Navin
Navin

Reputation: 105

"'NoneType' object is not iterable" error

Just wrote my first python program! I get zip files as attachment in mail which is saved in local folder. The program checks if there is any new file and if there is one it extracts the zip file and based on the filename it extracts to different folder. When i run my code i get the following error:

Traceback (most recent call last): File "C:/Zip/zipauto.py", line 28, in for file in new_files: TypeError: 'NoneType' object is not iterable

Can anyone please tell me where i am going wrong.

Thanks a lot for your time,

Navin Here is my code:

import zipfile
import os

ROOT_DIR = 'C://Zip//Zipped//'
destinationPath1 = "C://Zip//Extracted1//"
destinationPath2 = "C://Zip//Extracted2//"

def check_for_new_files(path=ROOT_DIR):

    new_files=[]
    for file in os.listdir(path):
        print "New file found ... ", file

def process_file(file):

    sourceZip = zipfile.ZipFile(file, 'r')
    for filename in sourceZip.namelist():
            if filename.startswith("xx") and filename.endswith(".csv"):
                    sourceZip.extract(filename, destinationPath1)
            elif filename.startswith("yy") and filename.endswith(".csv"):
                    sourceZip.extract(filename, destinationPath2)
                    sourceZip.close()

if __name__=="__main__":
    while True:
            new_files=check_for_new_files(ROOT_DIR)
            for file in new_files: # fails here
                    print "Unzipping files ... ", file
                    process_file(ROOT_DIR+"/"+file)

Upvotes: 1

Views: 15665

Answers (3)

TheFixer
TheFixer

Reputation: 369

Example, student_grade = dict(zip(names, grades)) make sure names and grades are lists and both having at least more than one item to iterate with. This has helped me

Upvotes: 0

John Machin
John Machin

Reputation: 82934

Here is the answer to your NEXT 2 questions:

(1) while True:: your code will loop forever.

(2) your function check_for_new_files doesn't check for new files, it checks for any files. You need to either move each incoming file to an archive directory after it's been processed, or use some kind of timestamp mechanism.

Upvotes: 1

phihag
phihag

Reputation: 287835

check_for_new_files has no return statement, and therefore implicitely returns None. Therefore,

new_files=check_for_new_files(ROOT_DIR)

sets new_files to None, and you cannot iterate over None.

Return the read files in check_for_new_files:

def check_for_new_files(path=ROOT_DIR):
    new_files = os.listdir(path)
    for file in new_files:
        print "New file found ... ", file
    return new_files

Upvotes: 7

Related Questions