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

    Join Date
    Oct 2017
    Posts
    85
    Rep Power
    1

    [Python 3] writing for loop txt file give strainge result, help needed!


    Hey Python Programmers...

    I try to write an for loop file as an .txt document... but it will be give an strainge result...
    This is my code, writting in python 3:

    Code:
    file = open("Doc.txt", "w")
    
    
    names = ["Jamie", "Vinnie", "Bennie", "Liesbeth", "Dylan", "Marvin", "Malaicka", "Chelsea"]
    
    for names in names:
        file.write(names)
    
    
    file.close()
    
    print(file)

    But my writting .txt document result as this:
    JamieVinnieBennieLiesbethDylanMarvinMalaickaChelsea
    If you can see, my list must be writted under each name... but it don't happend...

    Here an example for the result thad i want (writting on the forum, this is no .txt file:
    Jamie
    Vinnie
    Bennie
    Liesbeth
    Dylan
    Malaicka
    Chelsea
    This is an example for the just result about how it hearth, but my script doesn't this...
    Can anyone help me to correct my code, just i can expiriment with it ?...

    Thanks for help, Jamie.
  2. #2
  3. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,972
    Rep Power
    510
    Code:
    # You need new lines!  Here are a few ways to get them:
    
    names = ["Jamie", "Vinnie", "Bennie", "Liesbeth", "Dylan", "Marvin", "Malaicka", "Chelsea"]
    
    
    # python3
    
    with open("Doc.txt", "wt") as file:
        for name in names:
            print(name, file = file)  # print appends a new line
    
    
    # python3
    with open("Doc.txt", "wt") as file:
        file.write('\n'.join(names) + '\n')
    
    
    
    
    # And in any python version of this millennium,
    
    sink = open('Doc.txt', 'w')
    for name in names:
        sink.write(name + '\n')
    sink.close()
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo