Python只写第一行文件?

问题描述:

我以前张贴的问题iregards的程序文件组织信息:Is there a way to organize file content by list element in python?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

你在写失踪缩进 – Richard 2013-04-20 21:24:12

您只是在for循环之后写入文件,而不是每次写入一组数据。换句话说,您正在迭代所有数据,然后在打开文件,写入最后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()调用是不必要的。 first,last,houseactivity将已经是字符串。

with声明相结合,这整个事情可能崩溃到

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