在Python 2.7中同时将多个列表写入同一个.dat文件?

时间:2015-03-15 20:15:32

标签: python python-2.7 file-writing

这是我从伪代码的翻译。该代码表明可以将多个列表或数组写入.dat文件。我试图尽可能保持伪代码格式,以便我不会在调试过程中迷失方向。为了空间,我遗漏了实际的伪代码。我知道如何将所有内容写入.txt或.csv作为字符串,但是可以将它们写入同一个文件中,允许每个对象保持原始值吗?(Num = Num和str = str)

#THIS IS THE PREMISE OF THE PSEUDOCODE
#Cooper College maintains a master file of students and credits
#earned. Each semester the master is updated with a transaction
#file that contains credits earned during the semester.
#Each file is sorted in Student ID number order.

这就是我试图转换到PYTHON

#getReady()  
#   open master "studentFile.dat"
#   open trans "semesterCredits.dat"
#   open newMaster "updatedStudentFile.dat"
#   readMaster()
#   readTrans()
#   checkBoth()
#return
#
#readMaster()
#   input masterID, masterName, masterCredits from master
#   if eof then
#      masterID = HIGH_VALUE
#   endif
#return

这就是我试图创建一个启动程序文件

#EACH LIST HAS A RANGE OF [0, 4]
masterID =[100000,100001,100002,100003]
masterName =['Bevis, Ted','Finch, Harold','Einstein, Al','Queen, Liz']
masterCredits = [56,15,112,37]

master = open('studentFile.dat','wb')
master.write(masterID,masterName,masterCredits)
print master.readlines()


#THIS IS MY TRACEBACK ERROR

#Traceback (most recent call last):
#  File "C:/Users/School/Desktop/Find the Bugs Ch7/debug07-03start.py",     
#line 6, in <module>
#master.write(masterID,masterName,masterCredits)
#TypeError: function takes exactly 1 argument (3 given)

预期输出

print master.readlines()
[[100001,'Bevis, Ted',56],[100002,'Finch, Harold',15],[100003,'Einstein, Al',112]...]

2 个答案:

答案 0 :(得分:1)

您可以使用zip获取您的愿望清单:

>>> zip(masterID,masterName,masterCredits)
[(100000, 'Bevis, Ted', 56), (100001, 'Finch, Harold', 15), (100002, 'Einstein, Al', 112), (100003, 'Queen, Liz', 37)]

然后您只需循环压缩列表并写入文件:

with open('studentFile.dat','wb') as master:
    for i,j,k,z in zip(masterID,masterName,masterCredits) :
          master.write(','.join((str(i),j,k,str(z))))

答案 1 :(得分:0)

write接受一个字符串,然后传递一堆对象。这些需要在打印前转换为字符串。一种方法是

master.write(','.join([masterID,masterName,masterCredits]))

您可以从这些项目中创建一个列表,使用逗号连接它们并写入文件。