Python不会覆盖已经存在的文件/目录

bq9c1y66  于 2023-05-30  发布在  Python
关注(0)|答案(2)|浏览(122)

我使用Python从gmail下载图片附件,使用以下脚本:

#!/usr/bin/env python3
# read emails and detach attachment in attachments directory
 
import email
import getpass, imaplib
import os
import sys
import time
 
detach_dir = '.'
if 'attachments' not in os.listdir(detach_dir):
    os.mkdir('/var/www/html/attachments')
 
userName = 'enter-your-gmail-account-name-here'
passwd = 'enter-your-password-here'
 
try:
    imapSession = imaplib.IMAP4_SSL('imap.gmail.com',993)
    typ, accountDetails = imapSession.login(userName, passwd)
    if typ != 'OK':
        print ('Not able to sign in!')
        raise Exception
 
    imapSession.select('Inbox')
    typ, data = imapSession.search(None, 'SUBJECT', '"DASHBOARD"')
    if typ != 'OK':
        print ('Error searching Inbox.')
        raise Exception
 
    # Iterating over all emails
    for msgId in data[0].split():
        typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
 
        if typ != 'OK':
            print ('Error fetching mail.')
            raise Exception
 
        emailBody = messageParts[0][1] 
        mail = email.message_from_bytes(emailBody) 
 
        for part in mail.walk():
 
            if part.get_content_maintype() == 'multipart':
 
                continue
            if part.get('Content-Disposition') is None:
 
                continue
 
            fileName = part.get_filename()
 
            if bool(fileName): 
                filePath = os.path.join(detach_dir, '/var/www/html/attachments', fileName)
                if not os.path.isfile(filePath) : 
                    print (fileName)
                    print (filePath)
                    fp = open(filePath, 'wb')
                    fp.write(part.get_payload(decode=True))
                    fp.close()
 
    #MOVING EMAILS TO PROCESSED PART BEGINS HERE
    imapSession.select(mailbox='inbox', readonly=False)
    resp, items = imapSession.search(None, 'All')
    email_ids = items[0].split()
    for email in email_ids:
        latest_email_id = email
 
        #move to processed
        result = imapSession.store(latest_email_id, '+X-GM-LABELS', 'Processed')
 
        if result[0] == 'OK':
            #delete from inbox
            imapSession.store(latest_email_id, '+FLAGS', '\\Deleted')
 
    #END OF MOVING EMAILS TO PROCESSED
 
    imapSession.close()
    imapSession.logout()
 
except :
    print ('No attachments were downloaded')

我收到以下错误:

Traceback (most recent call last):
  File "/home/jenns/get_images_from_emails.py", line 12, in <module>
    os.mkdir('/var/www/html/attachments')
FileExistsError: [Errno 17] File exists: '/var/www/html/attachments'

我注意到python3不在#中!/usr/bin/env python3并将其更改为#!/usr/bin python3没有产生不同的结果。
我知道Gmail端正在工作,因为附件正在移动到已处理文件夹,电子邮件从我的收件箱中删除。
我也使用了sudo chmod 775 '/var/www/html/attachments',但这并没有解决问题。对于为什么不能使用脚本get_images_from_emails.py下载文件,有什么想法吗?

vql8enpb

vql8enpb1#

错误消息告诉您,您尝试创建的文件夹已经存在,而不是文件。文件将被覆盖。
这可能是由于在检查“detach_dir”是否存在时没有提供其完整路径,而是提供了创建它的完整路径。
类似这样的东西应该可以工作:

attach_dir =  '/var/www/html/attachments'
if not os.path.exists(attach_dir):
    os.makedirs(attach_dir)

编辑:
我不确定你的目录结构,但这看起来像是一个错误...

filePath = os.path.join(detach_dir, '/var/www/html/attachments', fileName)

...如上所述,您的“detach_dir”将是/var/www/html,因此文件路径将是:/var/www/html/var/www/html/attachments/filename(可能不存在的目录)

qfe3c7zg

qfe3c7zg2#

感谢@sm,这是一个有效的脚本!

#!/usr/bin/env python3
# read emails and detach attachment in attachments directory
 
import email
import getpass, imaplib
import os
import sys
import time
 
detach_dir =  '/var/www/html/attachments'
if not os.path.exists(detach_dir):
    os.makedirs(detach_dir)
 
userName = 'enter-your-gmail-account-name-here'
passwd = 'enter-your-password-here'
 
try:
    imapSession = imaplib.IMAP4_SSL('imap.gmail.com',993)
    typ, accountDetails = imapSession.login(userName, passwd)
    if typ != 'OK':
        print ('Not able to sign in!')
        raise Exception
 
    imapSession.select('Inbox')
    typ, data = imapSession.search(None, 'SUBJECT', '"DASHBOARD"')
    if typ != 'OK':
        print ('Error searching Inbox.')
        raise Exception
 
    # Iterating over all emails
    for msgId in data[0].split():
        typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
 
        if typ != 'OK':
            print ('Error fetching mail.')
            raise Exception
 
        emailBody = messageParts[0][1] 
        mail = email.message_from_bytes(emailBody) 
 
        for part in mail.walk():
 
            if part.get_content_maintype() == 'multipart':
 
                continue
            if part.get('Content-Disposition') is None:
 
                continue
 
            fileName = part.get_filename()
 
            if bool(fileName): 
                filePath = os.path.join(detach_dir, fileName)
                if not os.path.isfile(filePath) : 
                    print (fileName)
                    print (filePath)
                    fp = open(filePath, 'wb')
                    fp.write(part.get_payload(decode=True))
                    fp.close()
 
    #MOVING EMAILS TO PROCESSED PART BEGINS HERE
    imapSession.select(mailbox='inbox', readonly=False)
    resp, items = imapSession.search(None, 'All')
    email_ids = items[0].split()
    for email in email_ids:
        latest_email_id = email
 
        #move to processed
        result = imapSession.store(latest_email_id, '+X-GM-LABELS', 'Processed')
 
        if result[0] == 'OK':
            #delete from inbox
            imapSession.store(latest_email_id, '+FLAGS', '\\Deleted')
 
    #END OF MOVING EMAILS TO PROCESSED
 
    imapSession.close()
    imapSession.logout()
 
except :
    print ('No attachments were downloaded')

相关问题