python - How to write in new line in a file? -


i need create program saves people's information e.g. name in text file depending on first letter of surname if surname starts k goes myfile1.

i need loop have done because it's unknown number of people want each person written in different line in text file there way this.

the code @ bottom puts each separate information new line , don't want want each different person in new line.

myfile1 = open("al.txt", "wt") myfile2 = open("mz.txt", "wt") mylistal = ([]) mylistmz = ([])  while 1:      surname = input("enter surname name.")     if surname[0] in ("a","b","c","d","e","f","g","h","i","j","k","l"):         title = input("enter title.")         mylistal.append(title);         firstname = input("enter first name.")         mylistal.append(firstname);         mylistal.append(surname);         birthday = input("enter birthdate in mm/dd/yyyy format:")         mylistal.append(birthday);         email = input("enter email.")         mylistal.append(email);         phonenumber = input("enter phone number.")         mylistal.append(phonenumber);         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 title.")         mylistmz.insert(title);         firstname = input("enter first name.")         mylistmz.append(firstname);         mylistmz.append(surname);         birthday = input("enter birthdate in mm/dd/yyyy format:")         mylistmz.append(birthday);         email = input("enter email.")         mylistmz.append(email);         phonenumber = input("enter phone number.")         mylistmz.append(phonenumber);         line.write("\n")         item in mylistmz:             myfile2.write(line)      elif surname == "1":         break   myfile1.close() myfile2.close() 

you looking join.

when have list of items can join them in single string with.

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

produces

abc 

you can not use empty string string used separator

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

which produces

a, b, c 

in examples (for example first write)

myfile1.write(','.join(mylistal) + '\n') 

if happen have in list not string:

myfile1.write(','.join(str(x) x in mylistal) + '\n') 

(you can use map, generator expression suffices)

edit: adding map:

myfile1.write(','.join(map(str, mylistal)) + '\n') 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -