gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:34 24 4
gpt4 key购买 nike

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

# 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) 来搜索文件吗?

最佳答案

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)

关于python - 尝试从字典中查找以键名称开头的任何文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43753978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com