user5483229
user5483229

Reputation:

Trying to find any files that begin with a key name from a dictionary

Trying to find any files that begin with a key name from a dictionary. Current code:

# Example of student dictionary
students = {'lastName-firstName': '[email protected]', 'jones-bob': '[email protected]', 'doe-john': '[email protected]'}                

def files_to_attach():
    attachments = ['/Users/home/Downloads/Scale score ACER  copy.png']
    # Put file names from directory into a list
    # Example of files in list - f = ['lastName-firstName-pat-maths-plus-test-9-2017-03-22-10-23.png',
    #                                'lastName-firstName-pat-r-comprehension-test-9-2017-03-24-12-56.png',
    #                                'etc...']
    f = []
    for filenames in os.walk('/Users/home/Downloads/ACER-Results'):
        f.extend(filenames)
    # Find any files with student's name
    for key, value in students.iteritems():
        # UNSURE IF I NEED TO DO THIS???
        for files_to_attach in f:
            # If the start of the student file begins with the students key...
            if files_to_attach.startswith(key):
                # Add it to the attachments list.
                attachments.append(files_to_attach)
        # Sends email to parent with student's results attached
        send_mail(send_from, value, subject, text, attachments=[])

Getting this ERROR:

File "test.py", line 29, in files_to_attach
    if files_to_attach.startswith(key):
AttributeError: 'list' object has no attribute 'startswith'

Do I need to use a regular expression (re) to search the files?

Upvotes: 1

Views: 39

Answers (1)

Carles Mitjans
Carles Mitjans

Reputation: 4866

os.walk returns a tuple of (root, dirs, files) in a directory. In your code,

for filenanmes in os.walk(...):
    f.extend(filenames)

You are extending the list f with a tuple, so the final result of f will be a list of tuples. Later on, when you extract the contents of the list in

for files_to_attach in f:
    if files_to_attach.startswith(key):
        ...

here files_to_attach will be a tuple. What you should do is extract the contents of the tuple in the first for loop correctly:

for root, dirs, files in os.walk(...):
    for fi in files:
        f.append(fi)

or another option:

for fi in os.listdir(...):
    if os.path.isfile(fi): # Get the correct path to fi
        f.append(fi)

Upvotes: 0

Related Questions