在Python中的FTP服务器上用.txt文件的文本填充变量 [英] Fill variable with text of a .txt file at an FTP server in Python

查看:130
本文介绍了在Python中的FTP服务器上用.txt文件的文本填充变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我的问题听起来有点愚蠢,但是我对python编程还是很陌生.

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

我只想拥有一个文本变量,该变量将从FTP服务器上的.txt文件获取字符串.

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

因此,结论是:FTP服务器上存储了一个.txt文件,我想将此文件的内容存储在一个变量中...

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...

这是我到目前为止所拥有的...有人可以帮助我吗?我使用Python 3.6.3 :)预先感谢!

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

推荐答案

如果要在不使用任何临时文件的情况下将文本文件内容下载到内存,请使用

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)

这篇关于在Python中的FTP服务器上用.txt文件的文本填充变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆