I'm working with python console of QGIS 2.8.1
. I want to convert many xls
files into csv
format using python. My input directory is: D:\\PATRICIA\\TESTE\\XLS
and output is: D:\\PATRICIA\\TESTE\\CSV2
. I wrote this code based in your suggestions ( Converting xls file into csv/txt file in Python ) and developed it in differente files with different dates 1999/01/2
until 1999/01/31
as: RR_1999_1_2.xls
, RR_1999_1_3.xls
, ... RR_1999_1_31.xls
I don't know why my script doesn´t works. It means that nothing happened!
My script is :
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()
Any help?
Thanks.
Unless I've missed an important thing, you declare the function xls_to_csv
in a loop, but never call it. The general structure of your script should be:
#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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.