尝试从字典中查找以键名开头的任何文件

时间:2017-05-03 07:38:25

标签: python python-2.7 dictionary

尝试从字典中查找以键名开头的任何文件。目前的代码:

# Example of student dictionary
students = {'lastName-firstName': 'mum_email@optusnet.com.au', 'jones-bob': 'bob-jones@gmail.com', 'doe-john': 'dads_email@bigpond.net.au'}                

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=[])

获得此错误:

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

我是否需要使用正则表达式(re)来搜索文件?

1 个答案:

答案 0 :(得分:1)

os.walk在目录中返回(root, dirs, files)元组。在您的代码中,

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

您正在使用元组扩展列表f,因此f的最终结果将是元组列表。稍后,当您在

中提取列表的内容时
for files_to_attach in f:
    if files_to_attach.startswith(key):
        ...

这里files_to_attach将是一个元组。你应该做的是正确地在第一个for循环中提取元组的内容:

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

或其他选项:

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