如何解决使用ftplib在FTP中打开json文件
在我们的项目中,我们需要使用ftplib模块。我正在使用ftplib读取FTP中json文件的内容,但显示错误[Errno 2]没有这样的文件或目录:'test.json'
这是简单的代码:
from ftplib import FTP
networkconnect = 'ftp.test123.com'
usern = '123'
pwconnect = 'test123'
ftp = FTP(networkconnect,usern,pwconnect)
ftp.cwd('/testpath')
with open('test.json','r') as j:
json_data = json.load(j)
我尝试使用ftputil之类的其他模块,它会打开json文件
例如:
import ftputil
networkconnect = 'ftp.test123.com'
usern = '123'
pwconnect = 'test123'
test_host = ftputil.FTPHost(networkconnect,pwconnect)
test_host.chdir('/testpath')
with test_host.open('test.json','r') as j:
json_data = json.load(j)
但是由于我必须使用ftplib,所以我想知道是否有任何变通办法,以便使用ftplib在ftp中打开json文件?
提前谢谢大家
解决方法
尝试这种方式:首先将文件下载到本地,然后尝试将其打开。
currentDirectory = os.getcwd()
save_directory = os.path.join(currentDirectory,'file.json')
def download():
try:
ftp = ftplib.FTP('host','login','pass')
files = ftp.nlst()
filename = files[0] # get first file
ftp.retrbinary("RETR " + filename,open(save_directory,'wb').write)
ftp.close()
return True
except Exception as e:
print(e)
return False
if download():
with open(save_directory,'r') as j:
json_data = json.load(j)
,
我在 Raspberry Pi 2B 上运行它。它不涉及本地文件系统。它是 Python 2.x,我已将其精简为基础。远程文件内容被复制到本地 RAM,因此请注意源文件大小的内存限制。它在我的 23K 文件上运行良好。只能在 FTP(不是 SFTP)上运行。
# Comments: Read JSON stream from FTP.
import json
import ftplib,StringIO
if __name__ == '__main__':
ftpsite = 'ftp.yoursite.com'
ftplogin = 'yourlogin'
ftppsw = 'yourpassword'
ftpfilename = 'yourfile.json'
print('ftp {ftplogin}@{ftpsite}'.format(ftpsite=ftpsite,ftplogin=ftplogin))
print('retr {ftpfilename}'.format(ftpfilename=ftpfilename))
ftp=ftplib.FTP(ftpsite,ftplogin,ftppsw)
r = StringIO.StringIO()
ftp.retrbinary('retr ' + ftpfilename,r.write)
response = r.getvalue()
r.close()
ftp.quit()
parsed_json = json.loads(response)
print parsed_json
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。