【问题标题】:Retrieving files from a ftp server and append all of it into one excel file in python [duplicate]从ftp服务器检索文件并将所有文件附加到python中的一个excel文件中[重复]
【发布时间】:2017-11-29 23:27:28
【问题描述】:
from ftplib import FTP
import socket

ftp = FTP('***.*.***.***') 
ftp.login(user='someusername',passwd='somepassword')
ftp.cwd('fcst') // this is a subfolder on the ftp.No error here
i=4
filename='C:\Users\user\Desktop\INTERNSHIP\SOLAR_DADRI\data.xlsx'
localfile=open(filename,'wb')
while(i<7):
        j=1
        while(j<10):
            fileName='dadfrcst0'+str(j)+'0'+str(i)+'r2.xlsx'
            j=j+1
            ftp.retrbinary('RETR '+fileName,localfile.write,1024)


        i=i+1
ftp.close()
localfile.close()

所以我试图从 FTP 服务器检索文件并将它们全部写入一个 excel 文件。我想基本上追加,因为所有文件都具有相同的格式,并且我想做一个时间序列分析。

还只是让您知道服务器上的所有文件都是 excel 格式的文件是不同日期的文件,由我用来检索的正则表达式指定..即“dadrfcst0104r2.xlsx”表示 4 月 1 日的数据。

所以当我运行代码时,它显示文件大小很大,当我打开它时,它显示一个错误,然后只显示 4 月 1 日的数据。循环是正确的。那里没有错误。请帮忙。

【问题讨论】:

  • 您不能像这样附加xlsx 文件。
  • 或者使用不同的(更简单的)格式,比如 CSV。
  • 如果我使用 CSV,您能建议对我的代码进行修改吗?
  • 如果您使用 CSV,您的代码将按原样运行。

标签: python excel ftp append ftplib


【解决方案1】:

是否可以将文件附加为 .txt 文件? 好吧,这就是我在我的一个脚本中的做法

import datetime

today = datetime.datetime.today()
f = open(today.strftime("/home/pi/%Y/%b/%d-%b-%Y.txt"), "a")  #Append mode
f.write(str(today.strftime("%d-%b-%Y, %H:%M,"))) #Date an hour of event
f.write(str(pressure)+",")
f.write(str(temperature)+",")
f.write(str(humidity)+",")
f.write(str(energy)+",")                      #CSV format
f.close() #Close file

之后,我只是打开文件并在 excel 中处理它以创建一个表。不是很专业,只是作为一个初学者的意见

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2022-11-25
    相关资源
    最近更新 更多