Fill variable with text of a .txt file at an FTP server in Python

霸气de小男生 提交于 2019-11-27 07:26:11

问题


I think my question sounds kinda stupid but I'm pretty new to python programming.

I just want to have a text variable which gets a string from a .txt file at an FTP server.

So in conclusion: There is a .txt File stored at an FTP server and I want to have the content of this file stored in an variable...

This is what I have so far... Can anybody help me? I use Python 3.6.3 :) thanks in advance!

from ftplib import FTP

ftp = FTP('1bk2t.ddns.net')
ftp.login(user='User', passwd = 'Password')

ftp.cwd('/path/')

filename = 'filename.txt'

ftp.retrbinary("RETR " + filename, open(filename, 'wb').write)
ftp.quit()

var = localfile.read

回答1:


If you want to download a text file contents to memory, without using any temporary file, use FTP.retrlines like:

contents = ""
def collectLines(s):
    global contents
    contents += s + "\n"

ftp.retrlines("RETR " + filename, collectLines)

Or use an array:

lines = []
ftp.retrlines("RETR " + filename, lines.append)



回答2:


You can use StringIO as buffer for retrlines RETR:

import io

with io.StringIO() as buffer_io:
    ftp.retrlines(f'RETR {filename}', buffer_io.write)
    content = buffer_io.getvalue()


来源:https://stackoverflow.com/questions/47693770/fill-variable-with-text-of-a-txt-file-at-an-ftp-server-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!