I previously posted a question iregards to a program organizing information in a file: Is there a way to organize file content by list element in python?
I am now trying to write the information to a new file using the following code
def main():
#open the file
info = open('Studentinfo.txt', 'r')
#make file content into a list
allItems = []
#loop to strip and split
for i in info:
data = i.rstrip('\n').split(',')
allItems.append(data)
allItems.sort(key=lambda x: x[3]) # sort by activity
for data in allItems:
first = data[1]
last = data[0]
house = data[2]
activity = data[3]
a = str(first)
b = str(last)
c = str(house)
d = str(activity)
f = open('activites.txt', 'w')
f.write(a)
f.write(b)
f.write(c)
f.write(d)
f.close()
main()
however when i open the new text file instead of
Amewolo, bob J.,E2,none
Andrade, Danny R.,E2,SOCCER
Banks-Audu, Rob A.,E2,FOOTBALL
Anderson, billy D.,E1,basketball
souza, Ian L.,E1,ECO CLUB
Garcia, Yellow,E1,NONE
Brads, Kev J.,N1,BAND
Glasper, Larry L.,N1,CHOIR
Dimijian, Annie A.,S2,SPEECH AND DEBATE
there is only
Amewolo, bob J.,E2,none
why does python only write the first line
You are only writing to the file after the for loop instead of writing each set of data out one at a time. In other words, you're iterating over all the data, then after thate, you open the file, write the last 4 items, and then close it.
You need to open the file, write everything to it, and then close. Try this
f = open('activites.txt', 'w') # open the file first
for data in allItems: # iterate over all of the data
first = data[1]
last = data[0]
house = data[2]
activity = data[3]
a = str(first)
b = str(last)
c = str(house)
d = str(activity)
f.write(a) # write each element out
f.write(b)
f.write(c)
f.write(d)
f.close() # then close
However, the str()
calls are unnecessary. first
, last
, house
, and activity
will already be strings.
combining with the with
statement, this whole thing could collapse to
with open('activites.txt', 'w') as f:
for data in allItems:
data = [data[0], data[1]] + data[2:]
print(*data, file=f, sep=', ')
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.