需求:
code:
import os
import time
import numpy as np
def to_log_txt(filename):
if not os.path.exists('Out_file'):
os.makedirs('Out_file')
filename = filename + '.txt'
with open(filename, 'r', newline='') as f:
for line in f.readlines():
with open(filename, 'r', newline='') as w:
line_data = line.strip().split(',')
if len(line_data) == 6:
pass
def to_error_txt(filename):
input_filename = filename + '.txt'
with open(input_filename, 'r', newline='') as f:
if not os.path.exists('Out_file'):
os.makedirs('Out_file')
output_filename = filename + '_error.txt'
out_path = 'Out_file/' + output_filename
with open(out_path, 'w', newline='') as w:
flag = 1
for line in f.readlines()[1:]:
line_data = line.strip().split(',')
if len(line_data) != 6:
w.write('Line '+ str(flag) + ' in error: ' + line)
if len(line_data[0]) != 6:
if len(line_data) != 6:
pass
else:
w.write('Line '+ str(flag) + ' in error: ' + line)
flag+=1
w.close()
f.close()
def to_grade_txt(filename):
input_filename = filename + '.txt'
with open(input_filename, 'r', newline='') as f:
if not os.path.exists('Out_file'):
os.makedirs('Out_file')
output_filename = filename + '_grade.txt'
out_path = 'Out_file/' + output_filename
with open(out_path, 'w', newline='') as w:
w.writelines(" *************** " + '\n')
w.writelines(" Students Result " + '\n')
w.writelines(" *************** " + '\n')
w.writelines("Student Id Name Total Mark" + '\n')
w.writelines("---------- ---- ----------" + '\n')
remain_data = []
for line in f.readlines()[1:]:
line_data = line.strip().split(',')
if len(line_data) != 6:
pass
elif len(line_data[0]) != 6:
pass
else:
remain_data.append(line_data)
for i in range(len(remain_data)):
id = remain_data[i][0]
name = str(remain_data[i][1]) + ' ' + str(remain_data[i][2])
total_mark = float(remain_data[i][-3]) + float(remain_data[i][-2]) + float(remain_data[i][-1])
if i == 0:
pass
else:
w.writelines(str(id) + " " + name + " " + str(total_mark) + '\n')
w.close()
f.close()
if __name__ == '__main__':
filename = input('Enter the input filename without extension (X to exit):')
to_grade_txt(filename)
result:
get:
1.python在处理文本时,在遇到列表中的两数相加时,需要先将其转化为float类型;若转换失败,多半是因为float在转换int与string或str时,字符串中不允许存在空格或者引号
2.read与readlines;write与writelines的区别:
file.write(str)的参数是一个字符串,就是你要写入文件的内容.
file.writelines(sequence)的参数是序列,比如列表,它会迭代帮你写入文件。当然 也可以使字符串,但是要换行需尾加'\n'