简体   繁体   English

直接在FTP服务器上创建CSV文件

[英]Create a CSV file directly on an FTP server

I have created a CSV file using the Python csv library. 我已经使用Python csv库创建了一个CSV文件。

When all the CSV files are created, my second task is to put them on an FTP server. 创建所有CSV文件后,我的第二个任务是将它们放在FTP服务器上。

To achieve this, I generate all my files in the /tmp folder on my Linux computer, then I open an FTP connection and I upload them all to the remote server. 为此,我在Linux计算机的/tmp文件夹中生成了所有文件,然后打开了FTP连接,并将它们全部上传到远程服务器。

My question is: It is possible to create the CSV files in the memory buffer and put them directly on my FTP server? 我的问题是:是否可以在内存缓冲区中创建CSV文件并将其直接放在我的FTP服务器上?

Yes, you can generate files in memory using StringIO (or better cStringIO). 是的,您可以使用StringIO(或更好的cStringIO)在内存中生成文件。 You can try something like this: 您可以尝试如下操作:

import csv
from ftplib import FTP
from cStringIO import StringIO

...
ftp = FTP(host, user, passwd)
ftp.login()
output = StringIO()
data = csv.writer(output)
data.writerow(["data"] * 5)
output.seek(0)
ftp.storbinary("STOR data.txt", output)
...

Please note, this isn't fully workable code and you might need some changes depending on your FTP configuration. 请注意,这不是完全可行的代码,根据您的FTP配置,您可能需要进行一些更改。 For example, I had to add ftp.set_pasv(False) to make it work with my test FTP. 例如,我必须添加ftp.set_pasv(False)使其与我的测试FTP一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM