如何使用python直接将csv文件创建到ftp服务器?

时间:2018-09-19 12:40:22

标签: python python-3.x file ftp

具有用于创建csv文件并可以将其上传到ftp服务器的代码

use Test::More tests => 1;    # last test to print
use Test::Exception;
use Test::MockObject;

my $git;
BEGIN {
# pretend to have loaded the Git Module.
$DB::single=1;
$INC{'Git.pm'} = 1;
$git = Test::MockObject->new();
$git->fake_module('Git', repository => sub { $git } );
$git->set_true( qw(command command_oneline) );
}

use Import::Git;

 my $real_repo = Import::Git->init();
 $real_repo->targetdir('./');
 $real_repo->name('testrepo');
 $real_repo->git_import_user({ name => 'test', email => 'test@test.com', push_default => 'testpush' }); 
 $real_repo->create_repository();

但是我需要的是在计算机上不创建文件,我想直接向ftp服务器创建文件

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

您可以使csv编写器改为写入io.StringIO对象,然后在将其文本值编码为字节后将输出转换为io.BytesIO对象:

import io
csvfile = io.StringIO()
writer = csv.DictWriter(csvfile, fieldnames=csv_columns1) #csv_columns1 is a list of value to become  as heading
writer.writeheader()
for data in vals['details']:# values for the header
    writer.writerow(data)
writer = csv.DictWriter(csvfile, fieldnames=csv_columns2)#csv_columns1 is a list of value to become  as heading
writer.writeheader()
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)#csv_columns1 is a list of value to become  as heading
writer.writeheader()
for data in vals['OrderLine']:# values for the header
    writer.writerow(data)
    print(os.system('pwd'))

Output_Directory = "ftp_path_to_store_file"
username = "ftp_user_names"
password = "ftp_password"
ftp_ip = "ftp_host_ip"
a1 = 'STOR %s.csv' % (order.name)

try:
    ftp = FTP(ftp_ip)
    ftp.login(username, password)
    ftp.cwd(Output_Directory)
    ftp.storbinary('STOR ' + os.path.basename(csv_file), io.BytesIO(csvfile.getvalue().encode()))