我的python代码用于从.csv文件中获取数据并将其转换并保存到.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()
答案 0 :(得分:0)
由于旧文件已被覆盖,以前的数据已被删除。
为了保留现有数据,您需要通过' get_data(..)'重新读取数据,然后附加内容,并将所有数据保存回来。