我有一个程序,可以在电子表格中读取并操作一些东西,然后保存一个配置文件,以便您可以在将来恢复到您设置的相同格式。配置文件正在另存为 csv。
我遇到了一个问题,即一个数据集中的列中有逗号,这会破坏事情。所以我使用了to_csv和read_csv的"sep"参数来避免这个问题,但它仍然会发生。
这是导致问题的列名:["选择、计算或滑块标签"]
我使用"sep = '|' 来读取和写入 csv 文件,但问题仍然存在。
谢谢!
这是代码...
def fxThree_A(self):
# function to save column choices to file
# get name for configuration from user
#
# save values from list of active columns to .csv file
self.config_df = pd.DataFrame(columns = ['config_name','active_columns', 'inactive_columns'])
self.config_df.loc[0,'config_name'] = 'config_one'
self.config_df.loc[0,'active_columns'] = ','.join(self.columns_active)
self.config_df.loc[0,'inactive_columns'] = ','.join(self.columns_inactive)
self.config_df.to_csv(self.rootFolder + '__config.csv', sep = '|', index=False)
print(self.columns_inactive)
def fxThree_B(self):
# function to read column choices from file
# read in the config file
self.config_df = pd.read_csv(self.rootFolder + '__config.csv', sep = '|',)#, encoding='ISO-8859-1')
# display list of preset configurations
# pick which config to use from dropwdown
# apply stored settings to current columns
self.columns_active = self.config_df.loc[0,'active_columns'].split(",")
self.columns_inactive = self.config_df.loc[0,'inactive_columns'].split(",")
# change button colors to match the new values
for button in self.column_buttons:
if button.cget("text") in self.columns_active:
button.configure(bg = "light green")
elif button.cget("text") in self.columns_inactive:
button.configure(bg = "red")
# catch any buttons not in the list for some reason, i.e. if the file format changed since last time the config was saved
else:
button.configure(bg = "orange")
tk.messagebox.showerror("Alert", "File format changed since configuration was last saved. Please re-select columns and re-save your configuration.")
哦,
伙计。
这不是文件中的分隔符,而是我将列表连接成一个字符串的方式,以便将列表写出表的一个单元格。
我将这一行中的","更改为"||",这解决了问题。
self.config_df.loc[0,'inactive_columns'] = '||'.join(self.columns_inactive)
有时发布问题会让人感到清晰:)
我应该把这个留给别人吗?