[英]Error while decoding UTF-8 encoded csv file
第一次在这里发帖:)
我在尝试从 email 收件箱下载所有附件时遇到问题。 我下载它们,然后将它们写入我指定路径的文件中。 它非常适合直接下载到文件的.png 文件,但是当涉及到.csv 文件时,它给了我这个错误信息:
OSError: [Errno 22] 无效参数: 'C:\Users\antoi\OneDrive\Bureau\python_secge\=?UTF-8?B?RXh0cmFjdCBzZXggZ8OpIHB1YmxpYy0yMDIyLTAzLTI2LTAwLTAwLTI2LmNzdg==?='
我认为它不能很好地解码 csv 文件的名称,但我不知道为什么。
谢谢你的帮助!
如果你想看看我下面的代码:
import smtplib
import imaplib
import base64
import os
import email
smtp_address = 'smtp.gmail.com'
smtp_port = 465
email_user = 'XXXX'
email_pass = 'XXXXX'
mail = imaplib.IMAP4_SSL('imap.gmail.com',993)
mail.login(email_user, email_pass)
mail.select('Inbox')
type, data = mail.search(None, 'ALL')
mail_ids=data[0]
idlist=mail_ids.split()
for num in data[0].split():
typ, data = mail.fetch(num, '(RFC822)' )
raw_email = data[0][1]
# converts byte literal to string removing b''
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# downloading attachments
for part in email_message.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(r'C:\Users\antoi\OneDrive\Bureau\python_secge', fileName)
if not os.path.isfile(filePath) :
fp = open(filePath, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
subject = str(email_message).split("Subject: ", 1)
我试过把csv这个文件改个名字,下载的很好,但是里面的内容好像没解码一样:
# #*%%*525EE\ÿ ¿ A" ÿÄ7 ÿÚ iÙWúßóÓ ÅIq«‚ÙÊŸ§ˆ˜²‚6`ض p²#áíîŸÐà ¼ïDù÷.ŽéCÅ >ªþ®|…dÕË' <å8
!õÑàäH¬
从编码字语法1中窃取:
import re
import base64
import quopri
def encoded_words_to_text(encoded_words):
encoded_word_regex = r'=\?{1}(.+)\?{1}([B|Q])\?{1}(.+)\?{1}='
charset, encoding, encoded_text = re.match(encoded_word_regex,
encoded_words).groups()
if encoding == 'B':
byte_string = base64.b64decode(encoded_text)
elif encoding == 'Q':
byte_string = quopri.decodestring(encoded_text)
return byte_string.decode(charset)
申请如下:
filename = '=?UTF-8?B?RXh0cmFjdCBzZXggZ8OpIHB1YmxpYy0yMDIyLTAzLTI2LTAwLTAwLTI2LmNzdg==?='
encoded_words_to_text(filename)
'Extract sex gé public-2022-03-26-00-00-26.csv'
1并消除了SyntaxWarning: "is" with a literal。 您指的是 "==" 吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.