到目前为止,我有这个。我打开了数据文件,我能够从数据中创建一个列表,并正确地从列表中打印出我需要的数据。它出现在python中就好了。但是当我尝试将其写入txt文件时,它全部显示在1行上。不知道该怎么做,它在新文本文件中分为2列。
# open file
data = open("BigCoCompanyData.dat", "r")
data.readline()
# skip header and print number of employees
n = eval(data.readline())
print(n)
# read in employee information
longest = 0
# save phone list in text file
phoneFile = open("PhoneList.txt", "w")
for i in range(n):
lineI = data.readline().split(",")
nameLength = len(lineI[1])+len(lineI[2])
if nameLength > longest:
longest = nameLength
longest = longest + 5
print((lineI[2].title()+", "+lineI[1].title()).ljust(longest) + ("("+lineI[-2][0:3]+")"+lineI[-2][3:6]+"-"+lineI[-2][6:10]).rjust(14))
phoneFile.write((lineI[2].title()+", "+lineI[1].title()).ljust(longest) + ("("+lineI[-2][0:3]+")"+lineI[-2][3:6]+"-"+lineI[-2][6:10]).rjust(14))
data.close()
# close the file
phoneFile.close()
答案 0 :(得分:0)
phoneFile.write(...)
只是简单地写出你给它的那一行。每次你给出一行时,它都会将它附加到前一行,除非你用\n
结束你的行。
phoneFile.write((lineI[2].title()+", "+lineI[1].title()).ljust(longest) +
("("+lineI[-2][0:3]+")"+lineI[-2][3:6]+"-"+lineI[-2][6:10]).rjust(14)+'\n')