python-ftplib-retrbinaryæøå;
当我使用ftplib下载时,我对北欧字符“æå”有一个奇怪的问题 使用此部分代码时:python-ftplib-retrbinaryæøå;,python,special-characters,ftplib,Python,Special Characters,Ftplib,当我使用ftplib下载时,我对北欧字符“æå”有一个奇怪的问题 使用此部分代码时: source_file = 'file_w_æøå.zip' ftp.retrbinary('RETR %s' % source_file, open(local_file, 'wb').write) 我得到这个错误: return getattr(self._sock,name)(*args) UnicodeEncodeError: 'ascii' codec can't encode characters
source_file = 'file_w_æøå.zip'
ftp.retrbinary('RETR %s' % source_file, open(local_file, 'wb').write)
我得到这个错误:
return getattr(self._sock,name)(*args)
UnicodeEncodeError: 'ascii' codec can't encode characters u'\xe6' in position 12-14: ordinal not in range(128)
有趣的是,如果我用实际值替换字符串,如下所示:
ftp.retrbinary('RETR %s' % 'file_w_æøå.zip', open(local_file, 'wb').write)
文件下载没有问题
我已经尝试了utf-8解码/编码的几乎所有方法,但我只想尝试正确的方法:)
希望你们能帮忙:)
PS当在本地_文件变量中使用特殊字符时,它将不会出错
添加了完整的代码,不是完美的图片,仍然是一个新手:
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import ConfigParser
import ftplib
import codecs
sysCodec = sys.getfilesystemencoding()
print('sysCodec: %s' % sysCodec)
# Get the argument (a) Section in config file
extract_conf = sys.argv[1]
configParser = ConfigParser.SafeConfigParser()
configFilePath = r'C:\\FTP_DL\\config.ini'
configParser.read(configFilePath)
#set variable from Config file
try:
host = configParser.get(extract_conf, 'url')
#print('Host %s' % host)
user = configParser.get(extract_conf, 'user')
#print('User %s' % user)
pw = configParser.get(extract_conf, 'pw')
#print('PW %s' % pw)
ftp_dir = configParser.get(extract_conf, 'ftp_dir').decode('utf-8')
print('FTP_DIR: %s' % ftp_dir)
dest_dir = configParser.get(extract_conf, 'dest_dir').decode('utf-8')
print('DEST_DIR: %s' % dest_dir)
dest_file = configParser.get(extract_conf, 'dest_file').decode('utf-8')
print('DEST_FILE: %s' % dest_file)
source_file = configParser.get(extract_conf, 'source_file').decode('utf-8')
print('SOURCE_FILE: %s' % source_file)
local_file = os.path.join(dest_dir, dest_file)
print('Local_File: %s' % local_file)
except 'NoSectionError':
print ('Section %s not found' % extract_conf)
sys.exit()
ftp = ftplib.FTP(host)
ftp.login(user,pw)
ftp.cwd(ftp_dir)
ftp.retrbinary(retr, open(local_file, 'wb').write)
ftp.quit()
您使用的是Python2.x吗?编码是一场噩梦。仔细检查脚本的编码是否与shell的编码匹配,以避免很多麻烦。如果可能的话,在Python 2中使用unicode
u'youräöüstring'
,典型的缺陷是:Python脚本顶部缺少#编码:utf-8
,字符串前面缺少u”“
前缀。@Dschoni,我正在使用Python 2.7。听起来编码不容易,我很高兴听到这些。@LaurentPorte,我有#/usr/local/bin/python#-*-编码:utf-8-*-
在我的代码的前两行。@SebastianBuusJensen您是否有机会使用spyder进行开发?我将所有输入转换为unicode作为第一步,以便在脚本中有一个统一的编码。IDE有时在编辑器和shell中使用不同的编码,这使得调试更加困难。