python - Write csv to excel with pandas -


i have 13 csv files in folder called data, , want export csv's files in numerical order (1.csv,2.csv ...13.csv) excel file having each sheet named (1,2,3,4,5...13). tryed this:

from pandas.io.excel import excelwriter import pandas  ordered_files = ['1.csv', '2.csv','3.csv','4.csv', '5.csv','6.csv','7.csv', '8.csv','9.csv','10.csv', '11.csv','12.csv','13.csv']  excelwriter('my_excel.xlsx') ew:     csv_file in ordered_files:         pandas.read_csv(csv_file).to_excel(                         ew, index = false, sheet_name=csv_file, encoding='utf-8') 

and have 2 problems this:

  1. as see in list, can't import files directly folder data, if try:

    ordered_files = ['data/1.csv'] wont found valid csv.

  2. if use list method, sheet named 3.csv example instead of 3.

a side question, coming csv saw columns should int number format strings ' in front.

thank time! use python 3!

if concerns removing last 4 characters sheet names, use sheet_name=csv_file[:-4] in call to_excel. comment @pazqo shows how generate correct path find csv files in data directory.

more generally, suppose wanted process csv files on given path, there several ways this. here's 1 straightforward way.

import os glob import glob  def process(path, ew):     os.chdir(path) # note process-wide change     csv_file in glob('*.csv'):         pandas.read_csv(csv_file).to_excel(ew,                                            index = false,                                            sheet_name=csv_file[:-4],                                            encoding='utf-8')  excelwriter('my_excel.xlsx') ew:     process("data", ew) 

you might consider generating filenames using glob(os.path.join(path, "*.csv")) require remove leading path sheet names - possibly worthwhile avoid os.chdir call, bit ugly.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -