使用Python将字典打印到CSV文件

时间:2016-06-15 03:46:32

标签: python csv dictionary

我想将我的字典TimeSheet打印到我的CSV文件中。但是,它只将最后一行写入我的CSV文件。我怎样才能解决这个问题?我可以从控制台中的TimeSheet打印所有内容,但不能将所有字典打印打印到CSV。

import glob
import openpyxl
import csv
#loops through .xlsx files in folder path
path = 'C:/ExcelFolder/*.xlsx'
files = glob.glob(path)
for file in files:
    #selects specific cells in title sheet.
    wb = openpyxl.load_workbook(file)
    sheet = wb.get_sheet_by_name('Sheet2')
    Week = sheet.cell(row=1, column=1).value
    Date = sheet.cell(row=2, column=1).value
    Name = sheet.cell(row=4, column=2).value
    Title = sheet.cell(row=5, column=2).value
    Site = sheet.cell(row=6, column=2).value
    LocID = sheet.cell(row=7, column=2).value
    for n in range(2, 9):
        sheets = wb.worksheets[n]
        Days = wb.worksheets[n]
        for i in range(1, 57):
            From = sheets.cell(row=i, column=1).value
            To = sheets.cell(row=i, column=2).value
            Activity = sheets.cell(row=i, column=3).value
            TimeSheet = {'Week': Week, 'Date': Date, 'Name': Name, 'Title': Title, 'Site': Site, 'LocID': LocID, 'Days': Days, 'From': From, 'To': To, 'Activity': Activity}
            with open('TestOutput.csv', 'w') as csvfile:
                TimeSheet = {'Week': Week, 'Date': Date, 'Name': Name, 'Title': Title, 'Site': Site, 'LocID': LocID,
                             'Days': Days, 'From': From, 'To': To, 'Activity': Activity}
                fieldnames = ['Week', 'Date', 'Name', 'Title', 'Site', 'LocID', 'Days', 'From', 'To', 'Activity']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
                writer.writerow(
                    {'Week': Week, 'Date': Date, 'Name': Name, 'Title': Title, 'Site': Site, 'LocID': LocID, 'Days': Days, 'From': From, 'To': To, 'Activity': Activity})

                print(TimeSheet)

控制台输出:

{'Site': 'moon LV-426', 'Activity': None, 'From': datetime.time(18, 45), 'Title': 'Private Hudson', 'Week': 'Week 3', 'To': datetime.time(19, 0), 'Days': <Worksheet "Saturday">, 'Name': 'Bill Paxton', 'Date': '2016/5/22-2016/5/28', 'LocID': '4220A'}
{'Site': 'moon LV-426', 'Activity': None, 'From': datetime.time(19, 0), 'Title': 'Private Hudson', 'Week': 'Week 3', 'To': datetime.time(19, 15), 'Days': <Worksheet "Saturday">, 'Name': 'Bill Paxton', 'Date': '2016/5/22-2016/5/28', 'LocID': '4220A'}
{'Site': 'moon LV-426', 'Activity': None, 'From': datetime.time(19, 15), 'Title': 'Private Hudson', 'Week': 'Week 3', 'To': datetime.time(19, 30), 'Days': <Worksheet "Saturday">, 'Name': 'Bill Paxton', 'Date': '2016/5/22-2016/5/28', 'LocID': '4220A'}
{'Site': 'moon LV-426', 'Activity': None, 'From': datetime.time(19, 30), 'Title': 'Private Hudson', 'Week': 'Week 3', 'To': datetime.time(19, 45), 'Days': <Worksheet "Saturday">, 'Name': 'Bill Paxton', 'Date': '2016/5/22-2016/5/28', 'LocID': '4220A'}

CSV输出 enter image description here

3 个答案:

答案 0 :(得分:2)

问题可能是您为每次迭代重新创建CSV文件 当您移动CSV文件的创建时,它应该工作。从内循环出来的标题行如下:

import glob
import openpyxl
import csv

#loops through .xlsx files in folder path

with open('TestOutput.csv', 'w') as csvfile:
    fieldnames = ['Week', 'Date', 'Name', 'Title', 'Site', 'LocID', 'Days', 'From', 'To', 'Activity']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    path = 'C:/ExcelFolder/*.xlsx'
    files = glob.glob(path)    
    for file in files:
        #selects specific cells in title sheet.
        wb = openpyxl.load_workbook(file)
        sheet = wb.get_sheet_by_name('Sheet2')
        Week = sheet.cell(row=1, column=1).value
        Date = sheet.cell(row=2, column=1).value
        Name = sheet.cell(row=4, column=2).value
        Title = sheet.cell(row=5, column=2).value
        Site = sheet.cell(row=6, column=2).value
        LocID = sheet.cell(row=7, column=2).value
        for n in range(2, 9):
            sheets = wb.worksheets[n]
            Days = wb.worksheets[n]
            for i in range(1, 57):
                From = sheets.cell(row=i, column=1).value
                To = sheets.cell(row=i, column=2).value
                Activity = sheets.cell(row=i, column=3).value
                TimeSheet = {'Week': Week, 'Date': Date, 'Name': Name, 'Title': Title, 'Site': Site, 'LocID': LocID, 'Days': Days, 'From': From, 'To': To, 'Activity': Activity}                                                     
                writer.writerow(
                    {'Week': Week, 'Date': Date, 'Name': Name, 'Title': Title, 'Site': Site, 'LocID': LocID, 'Days': Days, 'From': From, 'To': To, 'Activity': Activity})
                print(TimeSheet)

答案 1 :(得分:1)

问题是&#39; TestOutput.csv&#39;每行都会打开&#39; w&#39;模式,将截断文件(请参阅https://docs.python.org/3/library/functions.html#open)。它只写最后一行,因为所有其他行都被删除了。

瞥一眼,你需要在遍历文件列表之前将调用移到open()和writeheader()。

答案 2 :(得分:1)

如前面的回复中所述,请事先创建CSV文件。

如果您希望单个csv合并来自excel文件的所有数据,DAXaholic的解决方案应该可以正常工作。

如果您希望每个excel文件都有一个csv文件,以下内容可能有所帮助:

import glob
import openpyxl
import csv
# loops through .xlsx files in folder path
path = 'C:/ExcelFolder/*.xlsx'
files = glob.glob(path)
fieldnames = ['Week', 'Date', 'Name', 'Title', 'Site', 'LocID', 'Days', 'From', 'To', 'Activity']
for file in files:
    # selects specific cells in title sheet.
    wb = openpyxl.load_workbook(file)
    sheet = wb.get_sheet_by_name('Sheet2')
    Week = sheet.cell(row=1, column=1).value
    Date = sheet.cell(row=2, column=1).value
    Name = sheet.cell(row=4, column=2).value
    Title = sheet.cell(row=5, column=2).value
    Site = sheet.cell(row=6, column=2).value
    LocID = sheet.cell(row=7, column=2).value

    # append the extension .csv to the current filename
    csvfilename = "{}.csv".format(file)
    with open(csvfilename, 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for n in range(2, 9):
            sheets = wb.worksheets[n]
            Days = wb.worksheets[n]
            for i in range(1, 57):
                From = sheets.cell(row=i, column=1).value
                To = sheets.cell(row=i, column=2).value
                Activity = sheets.cell(row=i, column=3).value
                TimeSheet = {'Week': Week, 'Date': Date, 'Name': Name, 'Title': Title, 'Site': Site, 'LocID': LocID, 'Days': Days, 'From': From, 'To': To, 'Activity': Activity}
                writer.writerow(TimeSheet)
                print(TimeSheet)