gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:16:06 24 4
gpt4 key购买 nike

我有一个代码来创建 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()))

关于python - 如何使用 python 创建 csv 文件直接到 ftp 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52406104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com