簡體   English   中英

Python:用UTF-8讀取Ftp文件列表?

[英]Python: Reading Ftp file list with UTF-8?

嗨,我正在使用模塊ftplib。 並使用以下代碼列出我的文件:

files=[]
files = ftp.nlst()

並使用以下代碼將它們寫入文本文件:

for item in files:
    filenames.write(item +'\n')

但是有一個編碼問題,如果我的文件名有'ı,ğ,ş'字符,它無法讀取這個並寫入文件'?' 代替。

如何正確閱讀?

Python 3.x使用默認編碼ISO-8859-1作為文件名。

要將UTF-8編碼用於服務器的文件名,您需要添加以下行:

ftpConnector = ftplib.FTP(host,user,password) # connection

ftpConnector.encoding='utf-8' #force encoding for file name in utf-8 rather than default that is iso-8889-1

然后你可以使用:

ftpConnector.storbinary( 'STOR '+fileName, file) # filename will be utf-8 encoded

在將項目寫入文件之前,需要將生成的項目轉換回unicode。 ftp模塊不支持unicode字符串。 要做到這一點嘗試:

import encodings.idna

for item in files:
    filenames.write(encodings.idna.ToUnicode(item) + '\n')
ftp.encoding='utf-8'
ftp.sendcmd('OPTS UTF8 ON')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM