python shutil: only copy part of the file -
the code read xls file directory, convert csv file , copy directory.
filepath = os.path.join('.', 'attachments') filepaths = [f f in os.listdir(filepath) if os.path.isfile(os.path.join(filepath, f)) , f.endswith('.xls')] f in filepaths: wb = xlrd.open_workbook(os.path.join(filepath, f)) sheet = wb.sheet_by_index(0) filename = f + '.csv' fp = open(os.path.join(filepath, filename), 'wb') wr = csv.writer(fp, quoting=csv.quote_all) rownum in xrange(sheet.nrows): wr.writerow(sheet.row_values(rownum)) fp.close shutil.copy(os.path.join('.', 'attachments', filename), new_directory)
the result is: xls file converted csv file, in new_directory, copied file contains part of csv file.
for example, original csv file has 30 rows, in copied file, there 17 rows. idea of why happen?
here's problem:
fp.close
you need call close
method, not reference method. so:
fp.close()
however, make life easier if use with
statements instead of trying figure out explicitly close
everything:
with open(os.path.join(filepath, filename), 'wb') fp: wr = csv.writer(fp, quoting=csv.quote_all) rownum in xrange(sheet.nrows): wr.writerow(sheet.row_values(rownum))
Comments
Post a Comment