我需要实现一个保存数据在txt,csv,bin和卸载它们的方法。我使用select_file
方法选择文件,该方法检查我选择的文件格式并调用相应的函数。
data = {
"name": heater.name,
"kW": heater.kW,
"sections": heater.sections,
"thermostat": heater.thermostat,
"cordLength": heater.cordLength,
"maxFanSpeed": heater.maxFanSpeed,
"isWaterFan": heater.isWaterFan,
"country": heater.country,
"manufacturer": heater.manufacturer,
"dm": heater.dm,
"state": heater.state,
}
CSV:
def save_csv_file(self, data): # Сэйв csv
filename = "heaters/" + f"heater{data['name'].upper()}.csv"
with open(filename, "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(
[
"Назва: ",
"Потужність: ",
"Секції: ",
"Термостат: ",
"Довжина шнуру: ",
"Максимальна кількість обертів: ",
"Це водний тепловетилятор: ",
"Країна-постачальник: ",
"Фірма-виробник: ",
"Діаметр: ",
"Стан: ",
]
)
writer.writerow(
[
data["name"],
data["kW"],
data["sections"],
"Наявний" if data["thermostat"] else "Відсутній",
data["cordLength"],
data["maxFanSpeed"],
"Так" if data["isWaterFan"] else "Ні",
data["country"],
data["manufacturer"],
data["dm"],
data["state"],
]
)
def load_csv_file(self, filename):
try:
with open(filename, "r", newline="") as file:
reader = csv.reader(file)
header = next(reader) # Skip the header row
expected_columns = [
"Назва: ",
"Потужність: ",
"Секції: ",
"Термостат: ",
"Довжина шнуру: ",
"Максимальна кількість обертів: ",
"Це водний тепловетилятор: ",
"Країна-постачальник: ",
"Фірма-виробник: ",
"Діаметр: ",
"Стан: ",
]
if header != expected_columns:
raise ValueError("Invalid CSV file format")
# Read the row containing the data
data_row = next(reader)
# Extract the values from the data row
data = {
"name": data_row[0],
"kW": data_row[1],
"sections": data_row[2],
"thermostat": True if data_row[3] == "Наявний" else False,
"cordLength": data_row[4],
"maxFanSpeed": data_row[5],
"isWaterFan": True if data_row[6] == "Так" else False,
"country": data_row[7],
"manufacturer": data_row[8],
"dm": data_row[9],
"state": data_row[10],
}
# Update the selected_heater attribute
self.selected_heater = FanHeater(
data["dm"],
data["manufacturer"],
data["country"],
data["maxFanSpeed"],
data["isWaterFan"],
data["name"],
data["kW"],
data["sections"],
data["thermostat"],
data["cordLength"],
data["state"],
)
# Display the heater details
HeaterGui.show_heater_details()
except FileNotFoundError:
print("File not found.")
BIN:
def save_binary_file(self, data):
filename = "heaters/" + f"heater{data['name'].upper()}.bin"
with open(filename, "wb") as file:
pickle.dump(data, file)
def load_binary_file(self, filename): # Загрузка bin
with open(filename, "rb") as file:
data = pickle.load(file)
return data
通过此函数选择文件:
def select_file(self):
filetypes = (
("Текстовый файл", "*.txt"),
("CSV файл", "*.csv"),
("Бинарный файл", "*.bin"),
)
filename = filedialog.askopenfilename(filetypes=filetypes)
if filename:
try:
heater = None
try:
heater = FanHeater()
heater.load_text_file(filename)
except FileNotFoundError:
try:
heater = FanHeater()
heater.load_csv_file(filename)
except FileNotFoundError:
try:
heater = FanHeater()
heater.load_binary_file(filename)
except FileNotFoundError:
messagebox.showerror("Error", "File not found")
if heater:
self.selected_heater = heater
self.show_heater_details()
except Exception as e:
messagebox.showerror("Error", str(e))
else:
messagebox.showerror("Error", "No file selected")
我试着仔细检查文件中的数据、变量的顺序等等。什么都不管用。错误:“列表索引超出范围”仍然存在。
我假设错误发生在这些行上:
if filename:
try:
heater = None
try:
heater = FanHeater()
heater.load_text_file(filename)
except FileNotFoundError:
try:
heater = FanHeater()
heater.load_csv_file(filename)
except FileNotFoundError:
try:
heater = FanHeater()
heater.load_binary_file(filename)
except FileNotFoundError:
messagebox.showerror("Error", "File not found")
if heater:
self.selected_heater = heater
self.show_heater_details()
except Exception as e: # Attention
messagebox.showerror("Error", str(e))
最有趣的是load_csv_file
函数本身没有调用,因为它留下了try(print不输出任何东西)。虽然从逻辑上讲,错误是由load_csv_file
的不正确处理引起的。
Traceback (most recent call last):
File "C:\Users\zurto\Desktop\ONPU\Python\lr5.py", line 785, in select_file heater.load_text_file(filename)
File "C:\Users\zurto\Desktop\ONPU\Python\lr5.py", line 98, in load_text_file self.cordLength = lines[4].strip()
Line 98:
self.cordLength = lines[4].strip()
1条答案
按热度按时间p5cysglq1#
错误发生在函数
select_file
中。因为文件找到了,但其格式不正确,程序试图将txt读取为csv,这就是列表索引超出范围的原因。修正后的函数如下所示: