assign之python文本处理
短信预约 -IT技能 免费直播动态提醒
需求:
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'
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341