当前位置: 动力学知识库 > 问答 > 编程问答 >

excel - How to download a .xls into a Python object via FTP with Python ftplib

问题描述:

I am new to Python, so forgive me if I am asking a wrong question. I have a .xls that I would like to ftp and save it as a Python object. Currently, I am taking an awkward approach where [Step 1] I first ftp the file and save it as .txt (I know .xls->.txt is a bad idea!), and then [Step 2] open and save that .txt file in Python shell. That is,

Step 1:

## Import the necessary module

from ftplib import FTP

ftp = FTP('webftp.vancouver.ca')

ftp.login()

ftp.cwd('OpenData/xls')

filename = 'new_food_vendor_locations.xls'

ftp.retrbinary('RETR %s' % filename, open('myLovelyNewFile.txt', 'w').write)

ftp.quit()

This allows me to create a new file 'myLovelyNewFile.txt' in my current directly. In my Python shell, I have:

Step 2:

myLovelyPython = open('myLovelyNewFile.txt','r')

for line in myLovelyPython.readlines():

print line

myLovelyPython.close()

Although Python can run all these command lines, the printed lines do not have correct inputs due to the forceful conversion from xls to txt. Furthermore, I would like to save the ftp-ed object directly as some python object (rather than first saving it as .txt outside Python). Is there easy solution to this problem?

网友答案:

Although I was looking for a way to directly purse the ftp-ed excel file into Python object, if I allows saving the excel file in my directory and re-read it again, the following works:

ftp = FTP('webftp.vancouver.ca')
ftp.login()
ftp.cwd('OpenData/xls')
filename = 'new_food_vendor_locations.xls'
ftp.retrbinary('RETR %s' % filename, open('myLovelyNewFile.xls', 'w').write)
ftp.quit()
workbook = xlrd.open_workbook('myLovelyNewFile.xls')
worksheet = workbook.sheet_by_name('Query_vendor_food')
num_rows = worksheet.nrows - 1
curr_row = -1
while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)
    print row

(I thank @jacoppens for his advice.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: