Albin
Albin

Reputation: 912

Add a new list in a new line on a .txt file in python

I'm trying to add a list to an existing .txt file in Python three. Currently I have the following code:

def function(list, new_add):
    with open("file.txt", new_add) as file:
        for item in list:
            file.write("{}\t".format(item))


add_grade(list, "w")

I have created a list:

list = [string1, integer1a, integer1b]

It works fine creating a new txt file. But if I replace "w" with "a" I do not get the purposed output. My question is now, how do I add new components of a list to the file in a new line? My current output look like this if I try to add new variables:

string1 integer1a integer1b string2 integer2a integer2a

I would like instead the following displayed:

string1 integer1a integer1b

string2 integer2a integer2a

...

How could I add a new line after the each list is inserted?

Upvotes: 1

Views: 120

Answers (2)

mhawke
mhawke

Reputation: 87134

You can do this quite easily with the Python 3 print() function, just specify the separator and file with the sep and file parameters, and print() will take care of the details for you:

def function(iterable, filename, new_add):
    with open(filename, new_add) as file:
        print(*iterable, sep='\t', file=file)

Note that I renamed the list parameter to iterable because using list shadows the built-in list class, and the function should work with any iterable.

This code will also work in Python 2 if you add the following to the top of your file:

from __future__ import print_function

Upvotes: 2

Neji Soltani
Neji Soltani

Reputation: 1511

this should work , you should call line break after writing your list in the file

def add_grade(list, new_add):
    with open("file.txt", new_add) as file:
        for item in list:
            file.write("{}\t".format(item))
        file.write("\n")


add_grade(list, "w")

Upvotes: 1

Related Questions