abh*_*nan 2 python ftp file python-3.x
我有一个代码来创建一个 csv 文件并且可以将它上传到 ftp 服务器
with open(csv_file, 'w') as csvfile:
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)
with open(csv_file, "rb") as f:
ftp.storbinary('STOR ' + os.path.basename(csv_file), f)
Run Code Online (Sandbox Code Playgroud)
但我需要的是没有在我的电脑上创建文件我想直接创建一个文件到 ftp 服务器
任何帮助,将不胜感激
您可以让 csv writer 写入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()))
Run Code Online (Sandbox Code Playgroud)