Python只写第一行文件?

时间:2013-04-20 21:21:06

标签: python python-3.x

我之前在文件中发布了一个组织信息的程序:Is there a way to organize file content by list element in python?

我现在正尝试使用以下代码将信息写入新文件

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()

但是当我打开新文本文件而不是

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

只有

 Amewolo, bob J.,E2,none

为什么python只写第一行

1 个答案:

答案 0 :(得分:4)

您只是在for循环之后写入文件,而不是一次一个地写出每组数据。换句话说,你正在迭代所有数据,然后在thate之后,你打开文件,写下最后4个项目,然后关闭它。

您需要打开文件,将所有内容写入其中,然后关闭。试试这个

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

但是,str()来电是不必要的。 firstlasthouseactivity已经是字符串。

with语句相结合,整个事情可能会崩溃到

with open('activites.txt', 'w') as f:
    for data in allItems:
        data = [data[0], data[1]] + data[2:]
        print(*data, file=f, sep=', ')