I am reading content from a file (scores.txt) and I have formatted the data that I need from it and I would like to write those lines to a new file. The new file I will be writing to is top_scores.txt. Below is the code for the desired output. I am just not entirely sure how to print to the file.
infile = open('scores.txt', 'r')
lineList = sorted(infile.readlines())
for lines in lineList:
newLine = lines.replace('\n', '')
splitLines = newLine.split(',')
studentNames = splitLines[0]
studentScores = splitLines[1:]
studentsList = []
for i in studentScores:
studentsList.append(int(i))
topScore = max(studentsList)
print(studentNames.capitalize() + ': ', studentsList, 'max score =', int(topScore))
Sample from scores.txt:
Pmas,95,72,77,84,86,81,74,\\n
Sample for desired input for new file:
Pmas: [95,72,77,84,86,81,74], max score = 95\\n
"(...) the variables I have defined to hold the data I need, are not defined (...)"
Maybe that's caused by lines like these:
for i in studentScores:
float(i)
float(i)
doesn't convert the value of i
in a "lasting" way unless you assign a variable to it; eg do score = float(i)
or whatever you want to call it. You can then work with score
which is now a floating point number.
When writing to files, like in the line below, you have to write a single string at a time. When you place a comma between the values, they won't be combined into a single string so python will most likely fail with a TypeError: function takes exactly 1 argument (x given)
.
infile2.write(studentNames.capitalize() + ': ', studentsList, 'top score =', int(topScore))
If studentNames
and studentsList
are list
s and int(topScore)
is an integer, none of the variables can be written to a file as is. You will need to select individual strings from your list
s (eg studentNames[0]
) or use " ".join(name_of_your_list)
to combine all elements into a single string. int(topScore)
will have to be converted to a string via str(topScore)
.
"I am just not entirely sure how to print to the file."
The easiest way to handle file reading/writing is via with open(filename, mode) handle:
. Eg:
with open("output_file.txt", "w") as f:
f.write(some_string)
Just some observations that'll explain at least some of the errors you're probably getting...
To write to a file just use :
file = open("top_score.txt", "a")
str=', '.join(str(x) for x in studentsList)
file.write(studentNames.capitalize() +'\t'+str+'\t'+(topScore))
file.close();
Here is a correct way to achieve what you want :
with open("scores.txt", 'r') as infile, open("top_score.txt", 'w') as outfile, open("top_score2.txt", '\
w') as outfile2:
lineList = sorted(infile.readlines())
for lines in lineList:
newLine = lines.replace('\n', '')
splitLines = newLine.split(',')
studentNames = splitLines[0]
studentScores = splitLines[1:]
studentsList = []
for i in studentScores:
if i == '':
break
studentsList.append(int(i))
topScore = max(studentsList)
result = "%s: %s,max score = %d" % (studentNames.capitalize(),
str(studentsList),
max(studentsList))
print(result)
print(result, file = outfile)
outfile2.write(result + "\n")
Note that I used two ways to print the result :
print()
file parameter. file.write()
method. Also note that I used a with
statement like jDo suggested.
This way, it permits to open a file and to automatically close it when exiting the block.
EDIT :
Here is a version that is even shorter :
with open("scores.txt", 'r') as infile, open("top_score.txt", 'w') as outfile, open("top_score2.txt", 'w') as outfile2:
lineList = sorted(infile.readlines())
for lines in lineList:
lines = lines.replace('\n', '').split(',')
studentScores = lines[1:-1]
studentsList = [int(i) for i in studentScores]
result = "%s: %s,max score = %d" % (lines[0].capitalize(),
str(studentsList),
max(studentsList))
print(result)
print(result, file = outfile)
outfile2.write(result + "\n")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.