【问题标题】:Can't upload a csv as Google Sheet with special characters in the contents无法将 csv 作为内容中包含特殊字符的 Google 表格上传
【发布时间】:2018-05-25 18:44:44
【问题描述】:

我一直在绞尽脑汁想弄清楚为什么我不能通过 API 服务将文件上传到谷歌驱动器。我已经指出这个问题与神奇宝贝中的特殊角色有关。如果我将其更改为常规 e,则上传文件没有问题。

我已经尝试过以下方法,但我完全失去了é。

.encode('ascii','ignore').decode('ascii')

有没有办法更改 API 用于上传文件的编码?我经常得到的错误是

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)

下面列出了我的示例代码

from httplib2 import Http
import io
from apiclient.discovery import build
from apiclient import errors
from apiclient.http import MediaFileUpload, MediaIoBaseDownload, MediaIoBaseUpload

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'

#performs authorization
authInst = auth(SCOPES,CLIENT_SECRET_FILE,APPLICATION_NAME)

#gets the credentials for use
credentials = authInst.getCredentials()

#sets up the drive service from which functions can be created
drive_service = build('drive', 'v3', http=credentials.authorize(Http()))

test = 'Pokémon, test, hello\nmark,john,kevin'.encode('ascii','ignore').decode('ascii')
fh = io.StringIO(test)
media = MediaIoBaseUpload(fh,
                          mimetype='text/csv',
                          resumable = False)
filename = 'csvtest'
file_metadata = {'name': filename, 'mimeType': 'application/vnd.google-apps.spreadsheet'}    
file = drive_service.files().create(body=file_metadata,\
                                          media_body=media,\
                                          fields='id').execute()
fileID = file.get('id')
print(fileID)

最后,我使用实际的 google Drive 手动完成了此操作,其中包含一个仅包含 Pokémon 的文件,并且我从未丢失 é,所以我觉得这一定是可能的。

【问题讨论】:

    标签: python encoding google-drive-api google-docs-api google-drive-shared-drive


    【解决方案1】:

    .encode('ascii','ignore')é 被忽略。那么如何使用 BytesIO 上传数据呢?请问您可以尝试修改如下吗?

    发件人:

    test = 'Pokémon, test, hello\nmark,john,kevin'.encode('ascii','ignore').decode('ascii')
    fh = io.StringIO(test)
    

    收件人:

    test = 'Pokémon, test, hello\nmark, john, kevin'.encode('utf-8')
    fh = io.BytesIO(test)
    

    参考:

    在我的环境中,这是可行的。但如果这不能解决您的情况,我很抱歉。

    【讨论】:

    • 是的,这行得通!我最初尝试过 BytesIO,但失败了。长话短说,我实际上正在使用 Pandas DataFrame,转换为 .csv,然后将其作为 Google 表格上传。这在 BytesIO 中失败了,因为 pandas .to_csv() 会生成一个字符串。阅读您的答案后,我意识到我可以通过将 .encode('utf-8') 添加到末尾并以这种方式上传来实现解决方案。再次感谢!
    • @Mike Lanza 很高兴您的问题得到了解决。也谢谢你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多