#python #pandas
Вопрос:
В основном, название. Метод pd.Dataframe.to_csv() отлично работает на моей машине вне кода приложения, но если я попытаюсь запустить его в графическом интерфейсе pyqt5, я получу следующую ошибку: Нет движка для типа файла: «csv». Ниже приведена функция, которая вызывает ошибку. Примечание: если пользователь предоставляет файл .xlsx, функция .to_excel() работает нормально. Имя файла, используемое функцией, передается через объект QFileDialog. Вот функция, вызывающая проблему.
def writeToFile(self, file, rows): try: new_df = pd.DataFrame(rows.items(), columns = ['Company Name', 'File Number'] ) if self.stack.currentIndex() == 0: if file[-4:] == '.csv': df = pd.read_csv(file) new_df = pd.concat([df, new_df]) else: df = pd.read_excel(file) new_df = pd.concat([df, new_df]) if file[-4] == '.csv': new_df.to_csv(file, index = False, compression = None) else: new_df.to_excel(file) if self.flag_uids == []: return "All emails were written to a file" else: s = "All emails possible were written to a file. There were " str(len(self.flag_uids)) " messages unable to be interpreted" return s except Exception as e: return e
Ответ №1:
возможно, код путает расширения, попробуйте разделить вещи.
def writeToFile(self, file, rows): try: new_df = pd.DataFrame(rows.items(), columns = ['Company Name', 'File Number'] ) if self.stack.currentIndex() == 0: if file[-4:] == '.csv': df_csv = pd.read_csv(file) new_df_csv = pd.concat([df_csv, new_df]) else: df_excel = pd.read_excel(file) new_df_excel = pd.concat([df_excel, new_df]) if file[-4] == '.csv': new_df_csv.to_csv(file, index = False, compression = None) else: new_df_excel.to_excel(file) if self.flag_uids == []: return "All emails were written to a file" else: s = "All emails possible were written to a file. There were " str(len(self.flag_uids)) " messages unable to be interpreted" return s except Exception as e: return e
Комментарии:
1. Спасибо за совет! Ошибка была вызвана функцией to_excel() в операторе else, потому что я поместил файл[4] == ‘.csv’ вместо файла[4:] == ‘.csv’