如何使用python将XLS转换为CSV文件?

时间:2015-08-18 10:37:17

标签: python excel csv xls qgis

我正在使用QGIS 2.8.1的python控制台。我想使用python将许多xls文件转换为csv格式。我的输入目录是:D:\PATRICIA\TESTE\XLS,输出为:D:\PATRICIA\TESTE\CSV2。我根据您的建议(Converting xls file into csv/txt file in Python)编写了此代码,并将其在不同日期1999/01/2的不同文件中开发,直到1999/01/31为:RR_1999_1_2.xlsRR_1999_1_3.xls ,. .. RR_1999_1_31.xls

我不知道为什么我的剧本不起作用。这意味着什么也没发生!

我的脚本是

import xlrd
import csv
import datetime as dt
from datetime import timedelta

#initial and final dates 
data1='19990102'
data2='19990131'

anoi = int(data1[:4])
mesi = int(data1[4:6])
diai = int(data1[6:8])
anof = int(data2[:4])
mesf = int(data2[4:6])
diaf = int(data2[6:8])

start_date = dt.datetime(anoi, mesi, diai)
end_date = dt.datetime(anof, mesf, diaf)

total_days = (end_date - start_date).days + 1


for day in xrange(0, total_days):
        current_date = (start_date + dt.timedelta(days = day)).date()
        file_date = str(current_date.year)+'_'+str(current_date.month)+'_'+str(current_date.day)

        srt1='D:/PATRICIA/TESTE/XLS/RR_'+file_date+'.xls'
        srt2='D:/PATRICIA/TESTE/CSV2/RR_'+file_date+'.csv'

        def xls_to_csv():

            x =  xlrd.open_workbook(str1)
            x1 = x.sheet_by_name('Sheet1')
            csvfile = open(str2, 'wb')
            writecsv = csv.writer(csvfile, quoting=csv.QUOTE_ALL)

            for rownum in xrange(sh.nrows):
                writecsv.writerow(x1.row_values(rownum))

            csvfile.close()

任何帮助?

感谢。

1 个答案:

答案 0 :(得分:0)

除非我错过了一件重要的事情,否则你在循环中声明函数xls_to_csv,但从不调用它。脚本的一般结构应该是:

#initializations
data1='19990102'
...
total_days = (end_date - start_date).days + 1

# function definition:
def xls_to_csv(str1, str2):
    x =  xlrd.open_workbook(str1)
    x1 = x.sheet_by_name('Sheet1')
    csvfile = open(str2, 'wb')
    writecsv = csv.writer(csvfile, quoting=csv.QUOTE_ALL)

    for rownum in xrange(sh.nrows):
        writecsv.writerow(x1.row_values(rownum))

    csvfile.close()

# loop
for day in xrange(0, total_days):
        current_date = (start_date + dt.timedelta(days = day)).date()
        file_date = str(current_date.year)+'_'+str(current_date.month)+'_'+str(current_date.day)

        srt1='D:/PATRICIA/TESTE/XLS/RR_'+file_date+'.xls'
        srt2='D:/PATRICIA/TESTE/CSV2/RR_'+file_date+'.csv'
        xls_to_csv(srt1, srt2)  # function call