0
我的Python代碼用於從.csv文件獲取數據並轉換並將其保存到.ods文件。問題是,當它保存到新文件時,它將刪除保存的文件中的其他工作表。如何在不刪除其他工作表的情況下更新新文件?如何創建/填充ods文件中的工作表而不破壞文件中的其他工作表?
import csv, shutil, os, glob
from pyexcel_ods3 import save_data
from collections import OrderedDict
# finds the latest file from my downloads folder
newest = max(glob.iglob('*.csv'), key=os.path.getctime)
my_file = open(newest)
file_reader = csv.reader(my_file)
file_data = list(file_reader)
# identifies the data structure
file_header = ['Details', 'Posting Date', 'Description', 'Amount', 'Type', 'Balance', 'Check or Slip #']
# compares the data structure in the csv file to the one used for this script
if file_data[0] == file_header:
del file_data[0] # removes the header form the csv file
date = file_data[0][1]
f_date = date.split('/')
f_date_formatted = '{}-{}-{}'.format(f_date[2], f_date[0], f_date[1])
for i in file_data: # organizes the data
i[4] = ''
transaction = float(i[3])
if transaction > 0:
i[3] = ''
i[4] = transaction
my_file.close()
# creates a copy of the unpopulated file. This file has 3 existing sheets. One sheet is called 'DATA'
shutil.copy('Checkbook Monthly balance.ods', 'Checkbook Monthly balance thru {}.ods'.format(f_date_formatted))
# populates the sheet called 'DATA'
data = OrderedDict()
data.update({'DATA': file_data})
save_data('Checkbook Monthly balance thru {}.ods'.format(f_date_formatted), data)
else:
print('It appears the bank changed the table format. Check the .csv file for a difference in the data structure.')
my_file.close()
我很感謝您的回覆。我對Python很新,並且對如何格式化這個問題掙扎不已。我明白你在說什麼。我只需要幫助格式。 – draugr
get_data('Checkbook Monthly balance.ods')也會返回一個字典:{'DATA':file_data}。 – chfw
好的。我能夠做我想要的,並保留其他工作表,但它從其他工作表中刪除所有格式。任何方式來保持格式? – draugr