如何编写一个Python程序,将txt文件中的数值转换为整数类型写入excel文件中?

问题描述 投票:0回答:1

该任务需要编写一个Python程序,从名为AI.txt的txt文件中读取6名学生两次不同考试的成绩数据,并将该文件的数据写入Excel中名为“qq”的工作表中文件。代码必须首先打开“AI.txt”文件,然后将当前行转换为列表。将cur列表中的数据写入“qq”表中,将数值数据转换为整数类型数据,并添加一列,其中前两列数据的平均值。最后将此 Excel 保存到名为“AI56.xlsx”的文件中。我遵守了上述要求,但是xlsx文件中两个分数列的数据仍然显示为文本类型而不是整数类型。我是 Windows 用户,使用 Anaconda 的环境编码和 PyCharm。 (我也是Python新手)

import openpyxl

with open('AI.txt', 'r') as file:
    lines = file.readlines()

workbook = openpyxl.Workbook()

sheet = workbook.create_sheet(title='qq')

for line in lines:
    
    cur = line.strip().split()

    
    sheet.append([int(val) for val in cur])


for row in sheet.iter_rows(min_row=2, max_col=2, max_row=sheet.max_row):
    for cell in row:
        cell.value = int(cell.value)

   
    avg_value = sum([cell.value for cell in row]) / len(row)
    sheet.cell(row=row[0].row, column=3, value=avg_value)


workbook.save('AI56.xlsx')

This how the txt file looks like This is the excel after running the code

我的代码使用列表理解将 cur 列表中的每个元素 val 转换为整数类型。但似乎仍然无法正常工作。仅平均列显示为整数类型。我错过了什么?

对于行中行:

cur = line.strip().split()

sheet.append([int(val) for val in cur])
python openpyxl txt anaconda3
1个回答
0
投票

只需使用 Pandas 并保持清洁即可:

import pandas as pd 
data = pd.read_csv('AI.txt', sep='\s+', index_col='Name')
data['mean']=  data.mean(axis=1)
data.to_excel('AI56.xlsx')
© www.soinside.com 2019 - 2024. All rights reserved.