Python 列表,.txt 文件
我还是个初学者,有几个问题想问。我有一个.txt文件,里面有名字和成绩,比如:
Emily Burgess 5 4 3 4
James Cook 4 9 5 4
Blergh Blargh 10 7 2 4
我需要把他们的名字、姓氏和平均成绩写到一个新的.txt文件里。然后我还需要计算所有人的平均成绩。我该怎么做呢?我已经开始做了,但接下来该怎么做我不太清楚:
def stuff():
things = []
file = open(r'stuff2.txt').read()
for line in file:
things.append(line.split(' '))
print(things)
for grade in things:
grades = int(grade[2], grade[3], grade[4], grade[5])
average = grades/4
print(average)
with open('newstuff.txt', 'w') as f:
f.write(things)
5 个回答
-1
使用pandas库:
import pandas
df = pandas.read_csv("stuff.txt", sep=" ", header=None, names=["first","last","grade1","grade2","grade3","grade4"])
df["average"] = (df["grade1"]+df["grade2"]+df["grade3"]+df["grade4"])/4.0
df.to_csv("newstuff.txt",sep=" ", index=False) #will print a header row, which you can disable with header=None
0
假设你原来的文本文件叫做 stuff2.txt,而你想把结果保存到一个新的文件 newstuff.txt 中:
def process_line(line):
line = line.split()
first = line[0]
last = line[1]
grades = [int(x) for x in line[2:]]
average = sum(grades) / float(len(grades))
return first, last, average
with open('stuff2.txt') as f:
lines = f.readlines()
with open('newstuff.txt', 'w') as f:
for line in lines:
first, last, avg = process_line(line)
f.write(first + " " + last + " " + str(avg) + "\n")
0
你的代码可以这样修改来正常工作:
with open('stuff2.txt') as f1, open('newstuff.txt', 'w') as f2:
for line in f:
raw_data = line.rstrip().split()
average = sum(int(i) for i in raw_data[2:])
new_data = ' '.join(raw_data[:2] + [str(average)])
f2.write(new_data)
1
编辑:因为你是刚开始学习Python的学生,我们暂时不讨论面向对象编程,但我会把下面的代码保留,以防你想稍微探索一下!
students = list() # initialize an accumulator list
with open("stuff2.txt") as infile:
for line in infile:
data = line.strip().split(" ")
# strip removes ending and beginning whitespace e.g. the ending \n and etc
datadict = {}
datadict['first'] = data[0]
datadict['last'] = data[1]
datadict['grades'] = data[2:]
students.append(datadict)
# this can all be done in one line, but it's much clearer this way
# after this, all your students are in `students`, each entry in `students` is a
# dictionary with keys `first`, `last`, and `grades`.
# OUTPUT
with open("newstuff.txt","w") as outfile:
for student in students:
outputline = ""
outputline += student['first']
outputline += " "
outputline += student['last']
outputline += ": "
outputline += ", ".join(student['grades'])
# ", ".join(list) gives you a string with every element of list
# separated by a comma and a space, e.g. ','.join(["1","2","3"]) == "1, 2, 3"
outputline += "|| average: "
average = str(sum(map(int,student['grades']))/len(student['grades']))
# since student['grades'] is a list of strings, and we need to add them, you
# have to use map(int, student['grades']) to get their int representations.
# this is equivalent to [int(grade) for grade in student['grades']]
outputline += average
outputline += "\n"
outfile.write(outputline)
# again, this can be done in one line
# outfile.write("{0['first']} {0['last']}: {1}||{2}\n".format(
# student, ', '.join(student['grades']), sum(map(int,student['grades']))/len(student['grades']))
# but, again, this is long and unwieldy.
我一直支持在这类应用中使用类。
class Student(object):
def __init__(self,name=None,grades=None,initarray=None):
"""Can be initialized as Student(name="Name",grades=[1,2,3]) or
Student(["First","Last",1,2,3])"""
if not (name and grades) or (initarray):
raise ValueError("You must supply both name and grades, or initarray")
if (name and grades):
self.name = name
self.grades = grades
else:
self.name = ' '.join(initarray[:2])
self.grades = initarray[2:]
@property
def average(self):
return sum(self.grades)/len(self.grades)
然后你可以做一些像这样的事情:
students = list()
with open(r"stuff2.txt",'r') as f:
for line in file:
students.append(Student(line.strip().split(" ")))
# students is now a list of Student objects
你可以用以下方式把它们全部写入一个文件:
with open("students_grades.txt","w") as out_:
for student in students:
out_.write(r"{student.name}: {45:grades}||{student.average}\n".format(
student=student, grades = ', '.join(student.grades)))
不过如果你想以后再用这些对象,可能需要把它们“腌制”一下。
import pickle
with open("testpickle.pkl","wb") as pkl:
pickle.dump(students,pkl)
然后可以用以下方式再次使用它们:
import pickle # if you haven't already, obviously
with open('testpickle.pkl','rb') as pkl:
students = pickle.load(pkl)
1
这段话的意思是,虽然不太好判断,但看起来你的 for
循环里有一些问题。比如说,你不能用四个参数来调用 int
的构造函数:
TypeError: int() takes at most 2 arguments (4 given)
你是不是想这样:
grades = [int(g) for g in grades[1:]]
average = sum(grades) / len(grades[1:])
呢?