#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    25
    Rep Power
    0

    Write to new line.


    I'm trying to write some data to a file. I have the code to do this but it outputs to one continuous line. How do I write to the next line?

    Code:
     #!/usr/bin/python
    import json
    
    f = open('test.dat', 'r')
    json_obj = json.load(f)
    f.close()
    fp=open('testing1.dat', 'w')
    for record in json_obj:
        fp.write(record[u'id']+","+record[u'name']+",")
    fp.close()
    I've tried inserting /n in the fp.write statement but I receive various errors on placement.

    I've tried writing the record to a string.
    Code:
     #!/usr/bin/python
    import json
    
    f = open('test.dat', 'r')
    json_obj = json.load(f)
    f.close()
    fp=open('testing1.dat', 'w')
    for record in json_obj:
        string= "%s,%s\n" %(record[u'id']+","+record[u'name']+",")
        fp.write(string)
    fp.close()
    This returns the error.
    TypeError: not enough arguments for format string

    Thank you for any help.
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    610
    Rep Power
    65
    Try ...
    Code:
    #!/usr/bin/python
    import json
    
    f = open('test.dat', 'r')
    json_obj = json.load(f)
    f.close()
    fp=open('testing1.dat', 'w')
    for record in json_obj:
        s = "%s,%s\n" % (record[u'id'],record[u'name'])
        fp.write(s)
    fp.close()

    Comments on this post

    • skyblues agrees : Spot on. Many thanks for the help.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    25
    Rep Power
    0

    Smile


    Originally Posted by Dietrich
    Try ...
    Code:
    #!/usr/bin/python
    import json
    
    f = open('test.dat', 'r')
    json_obj = json.load(f)
    f.close()
    fp=open('testing1.dat', 'w')
    for record in json_obj:
        s = "%s,%s\n" % (record[u'id'],record[u'name'])
        fp.write(s)
    fp.close()
    Thank you very much Dietrich it now works The "," were the problem.

IMN logo majestic logo threadwatch logo seochat tools logo