开发者

moving from one csv worksheet to the next in a python script

开发者 https://www.devze.com 2023-03-08 16:01 出处:网络
I\'ve been using excel to create .csv workesheets that I\'d like to parse using python. Each worksheet is named after a shop (e.g worksheet 1: \"Waitrose\", worksheet 2: \"Tesco\", worksheet 3: \"Asda

I've been using excel to create .csv workesheets that I'd like to parse using python. Each worksheet is named after a shop (e.g worksheet 1: "Waitrose", worksheet 2: "Tesco", worksheet 3: "Asda") and contains a list of products (column 1) and their associated prices (column 2). I've written a python script that can access a worksheet and turn the contents into a dictionary (see below) but am struggling to find a way to get the program to access the next worksheet in the workbook. I want to end up with as many dictionaries as worksheets. The csv module doesn't seem to be of much help and I can't find a current third party python 3-compatible module that deals with excel. I was thinking mayb开发者_运维知识库e applescript but am not sure how I'd embed this in a python script

waitrose = {'apples' : 25, 'oranges' : 45 etc}

any suggestions?

paul.


Each worksheet must be saved as a separate CSV. Since you are already able to parse a single CSV I'll concentrate on handling the individual files. Once you have a CSV for each Excel worksheet, you can iterate through each .csv file in a directory using the glob module. With glob.glob() you can use wildcards in the path, so if you want just the .csv files in a directory use the *.csv wildcard.

import glob
import os

for csvFilename in glob.glob("C:\\path-to-folder-with-csv\\*.csv"):
    # csvFilename now contains the full path to the next CSV in the folder

    # This will give us the basename of the file without the extension
    worksheet = os.path.basename(os.path.splitext(csvFilename)[0])

    if worksheet.lower() == "waitrose":
        # Parse Waitrose CSV...

    elif worksheet.lower() == "tesco":
        # Parse Tesco CSV...

    elif worksheet.lower() == "asda":
        # Parse Asda CSV...


I've not used it but have you looked at the xlrd module? It appears to handle reading regular Excel files including Worksheets.

https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号