[英]how can i create a csv file directly to ftp server using python?
我有一個代碼來創建一個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)
但是我需要在計算機上不創建文件的情況下直接將文件創建到ftp服務器
任何幫助,將不勝感激
您可以使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()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.