By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,587 Members | 1,677 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

Need help writing to a text file in Python

telgroc
P: 3
I need to use a pre-existing list of strings in the format stated below. these strings need to be written to a text file called "input.txt"
(so basically, there are 3 lines of data for each student and each of the fields is separated by a comma)

<first name>,<middle name>,<last name>,<box number>
<number>,<street>,<city>,<state>,<zip code>
<gpa>

so far I have:
Expand|Select|Wrap|Line Numbers
  1. listOfStrings=['Samuel','C.','Young','9614','\n','24','Overlook Park','Philadelphia','PA','43278','\n','3.04','\n]
  2. fh=open("input.txt",'w')
  3. fh.write(listOfStrings)
  4. fh.close()
  5.  
but that outputs:
SamuelC.Young9614
24OverlookParkPhiladelphiaPA43278
3.04

so how do I get commas in there? Thanks in advance.
Oct 28 '08 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
Join the list of strings with a space character. Split the string on " \n ". Then:
Expand|Select|Wrap|Line Numbers
  1. '\n'.join([','.join(item.strip().split()) for item in outputList])
Oct 28 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.