简体   繁体   中英

How to write in new line in a file?

I need to create a program that saves people's information eg their name in a text file depending on the first letter of their surname so if their surname starts with a K it goes into MyFile1 .

I need it to loop like I have done because it's an unknown number of people however I want each person to be written in a different line in the text file is there a way to do this.

The code at the bottom puts each separate information into a new line and I don't want that I want each different person to be in a new line.

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

You are looking for join .

When you have a list of items you can join them in a single string with.

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

produces

abc

You can not only use the empty string but also another string which will be used as separator

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

which now produces

a, b, c

In your examples (for example the first write )

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

If you happen to have something in the list which is not a string:

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

(you can also use map , but a generator expression suffices)

Edit: adding the map :

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

In your case I would rather use a list of dictionaries, where a person with all its infos is a dictionary. Then you can convert it to a JSON string, which is a standard format for representing data. (Otherwise you need to define your own format, with delimiters between the items.)

So something like this:

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

Parsing a json is also very easy after all:

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

You can use in your code for the decision in which array it should be written something like this:

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

This will make your script more clear and robust.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM