如何在文件中添加新行?

时间:2016-01-16 09:03:52

标签: python

我需要创建一个程序来保存人们的信息,例如他们的姓名在文本文件中取决于姓氏的第一个字母,因此如果他们的姓氏以K开头,则会进入MyFile1

我需要它像我一样循环,因为它是一个未知数量的人但是我希望每个人都写在文本文件的不同行中是否有办法做到这一点。

底部的代码将每个单独的信息放入一个新行,我不希望我希望每个不同的人都在一个新的行。

MyFile1 = open("AL.txt", "wt")
MyFile2 = open("MZ.txt", "wt")
myListAL = ([])
myListMZ = ([])

while 1: 
    SurName = input("Enter your surname name.")
    if SurName[0] in ("A","B","C","D","E","F","G","H","I","J","K","L"):
        Title = input("Enter your title.")
        myListAL.append(Title);
        FirstName = input("Enter your first name.")
        myListAL.append(FirstName);
        myListAL.append(SurName);
        Birthday = input("Enter birthdate in mm/dd/yyyy format:")
        myListAL.append(Birthday);
        Email = input("Enter your email.")
        myListAL.append(Email);
        PhoneNumber = input("Enter your phone number.")
        myListAL.append(PhoneNumber);
        for item in myListAL:
            MyFile1.write(item+"\n")

    elif SurName[0] in ("M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"):
        Title = input("Enter your title.")
        myListMZ.insert(Title);
        FirstName = input("Enter your first name.")
        myListMZ.append(FirstName);
        myListMZ.append(SurName);
        Birthday = input("Enter birthdate in mm/dd/yyyy format:")
        myListMZ.append(Birthday);
        Email = input("Enter your email.")
        myListMZ.append(Email);
        PhoneNumber = input("Enter your phone number.")
        myListMZ.append(PhoneNumber);
        line.write("\n")
        for item in myListMZ:
            MyFile2.write(line)

    elif SurName == "1":
        break


MyFile1.close()
MyFile2.close()

2 个答案:

答案 0 :(得分:2)

您正在寻找join

如果您有一个项目列表,可以将它们加入一个字符串中。

l = ['a', 'b', 'c']
print(''.join(l))

产生

abc

您不仅可以使用空字符串,还可以使用另一个将用作分隔符的字符串

l = ['a', 'b', 'c']
print(', '.join(l))

现在生成

a, b, c

在您的示例中(例如第一个write

MyFile1.write(','.join(MyListAL) + '\n')

如果您恰好在列表中有一些不是字符串的东西:

MyFile1.write(','.join(str(x) for x in MyListAL) + '\n')

(您也可以使用map,但生成器表达式就足够了)

修改:添加map

MyFile1.write(','.join(map(str, MyListAL)) + '\n')

答案 1 :(得分:1)

在你的情况下,我宁愿使用一个词典列表,其中一个人的所有信息都是字典。然后,您可以将其转换为JSON字符串,这是表示数据的标准格式。 (否则,您需要定义自己的格式,并在项目之间使用分隔符。)

这样的事情:

import json # at the top of your script

# I would create a function to get the information from a person:
def get_person_input():
   person = {}
   person["surname"] = input("Surname: ")
   person["title"] = input("Title: ")
   person["email"] = input("Email: ")
   # TODO: do whatever you still want

   return person


# Later in the script when you want to write it to a file:
new_line = json.dumps( person )

myfile.write( new_line + "\n" )

毕竟解析一个json也很容易:

person = json.loads(current_line) # you can handle exception if you want to make sure, that it is a JSON format

您可以在代码中使用它来决定应该编写的数组:

SurName = input("Enter your surname name.")
if SurName[0] <= 'L':
    ...
else:
    ...

这将使您的脚本更加清晰和健壮。