【问题标题】:Print Dictionary to CSV file with Python使用 Python 将字典打印到 CSV 文件
【发布时间】:2016-06-15 03:46:31
【问题描述】:

我想将我的字典 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 输出:

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    问题可能是您为每次迭代重新创建 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)
    

    【讨论】:

    • 我明白你的意思,但是当我将 open 调用移到内部循环时,没有任何内容打印或写入 csv 文件。
    • 我说的不是把它移到内循环而是移出循环
    • 啊,我明白了,谢谢。
    【解决方案2】:

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

    一目了然,在遍历文件列表之前,您需要将调用移至 open() 和 writeheader()。

    【讨论】:

      【解决方案3】:

      如之前的回复所述,请事先创建 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)
      

      【讨论】:

        猜你喜欢
        • 2019-11-04
        • 1970-01-01
        • 2020-02-26
        • 1970-01-01
        • 2017-12-24
        • 2017-10-26
        • 1970-01-01
        • 1970-01-01
        • 2015-07-08
        相关资源
        最近更新 更多