user3362804
user3362804

Reputation: 27

Python 3.3 Writing A String From A List To A txt File

I am trying to write a string from a list to a text file over new lines

The string is stored in the list as follows

name:emailaddress:mobilenumber

I have a repr in a class which prints out a readable string to the screen so if the user wants to print the contacts to screen they will print as follows:

Name - Email Address - Mobile Number

I can write to the text file as Name - Email Address - Mobile Number

but I want to write to the text file as follows:

Name
Email Address
Mobile Number

I'm not sure how to strip out the "-"

The code I have so far is as follows:

file = open("StaffData.txt", "w")
for contacts in staffList :
   file.write(str(contacts) + "\n")
file.close()

Any guidance would me much appreciated

Upvotes: 1

Views: 209

Answers (1)

Roberto
Roberto

Reputation: 9070

If I understood correctly, you could do something like:

with open("StaffData.txt", "wt") as file:
    for contacts in staffList :
       file.write("\n".join(str(contacts).split(' - ')) + "\n")

EDIT: According to last question update, every field goes in a different line

Upvotes: 1

Related Questions