# 代码段1 csv_file = open('score.csv') lines = [] for line in csv_file: line = line.replace('\n','') lines.append(line.split(',')) print(lines) csv_file.close() # 代码段2 csv_file = open('score.csv') file_new = open('count.csv','w+') lines = [] for line in csv_file: line = line.replace('\n','') lines.append(line.split(',')) # 添加表头字段 lines[0].append('总分') # 添加总分 for i in range(len(lines)-1): idx = i+1 sun_score = 0 for j in range(len(lines[idx])) : if lines[idx][j].isnumeric(): sun_score += int(lines[idx][j]) lines[idx].append(str(sun_score)) for line in lines: print(line) file_new.write(','.join(line)+'\n') csv_file.close() file_new.close()# 基于代码段1与代码段2,在csv中第7列即G列增加平均分列 # 注意:方法借鉴代码段2进行修改
时间: 2024-01-25 12:03:51 浏览: 54
可以在代码段2中添加以下代码来实现在csv中第7列即G列增加平均分列:
```
# 添加平均分
lines[0].append('平均分')
for i in range(1, len(lines)):
sum_score = 0
count = 0
for j in range(1, len(lines[i])):
if lines[i][j].isnumeric():
sum_score += int(lines[i][j])
count += 1
avg_score = round(sum_score / count, 2) if count != 0 else 0
lines[i].append(str(avg_score))
# 将处理后的数据写入新文件
for line in lines:
file_new.write(','.join(line)+'\n')
```
注意,这里假设第1行为表头,从第2行开始计算平均分。同时,当某个学生的成绩都为空时,平均分设为0。
相关问题
import csv with open(r'C:\Users\Administrator\Downloads\Shanghai_Dialect_Scripted_Speech_Corpus_Daily_Use_Sentence') as infile: stripped = (line.strip() for line in infile) lines = (line.split(",") for line in stripped if line) with open('output.csv', 'w') as outfile: writer = csv.writer(outfile) writer.writerows(lines) SyntaxError: invalid syntax
这段代码存在一个语法错误,需要加上文件的读取模式。应该修改为:
```
import csv
with open(r'C:\Users\Administrator\Downloads\Shanghai_Dialect_Scripted_Speech_Corpus_Daily_Use_Sentence.csv', 'r') as infile:
stripped = (line.strip() for line in infile)
lines = (line.split(",") for line in stripped if line)
with open('output.csv', 'w') as outfile:
writer = csv.writer(outfile)
writer.writerows(lines)
```
这样代码就可以正确读取文件,并将数据写入一个名为 `output.csv` 的 CSV 文件中。
阅读全文