abagelwon
abagelwon

Reputation: 3

how to write items in string on a new line

I'm very new to python, so please bear with me while I try to explain my problem :)

Instructions given:

  1. for each item in "list", write that item in a new line to the end of the file specified by "filename."
  2. list = [this, is, a, sentence]
  3. def newlines (filename, list):

I've found online a code that works, but it involves f.seek(0) and we haven't learned to use seek or to place a number inside the (). I was just wondering if there was another "simpler" way to write this.

Thanks in advance!

Upvotes: 0

Views: 497

Answers (3)

minitechi
minitechi

Reputation: 144

Here is my answer. You can try this out and change your code accordingly.

def newlines(filename,list):
f=open(filename+".txt","w+")
for i in list:
    f.write(i+"\n")
f.close()

ls = [this, is, a, sentence]
newlines("test",ls)

Upvotes: 0

Suraj
Suraj

Reputation: 2477

with open('filename.txt', 'w') as f:
    for item in l:
        f.write(item+'\n')

If this is the only list you want to write to the file, use 'w' option. Else you can use the append 'a' option to append strings to the end of the file.

Based on @Jon Clements's comment, you can replace the for loop as follows :

with open('filename.txt', 'w') as f:
    print(*the_list, sep='\n', file=f)

Upvotes: 0

Hades1598
Hades1598

Reputation: 320

I'm not sure if this is what you want. But let me put my answer here for you to check.

def newlines(l):
    f = open("newfile.txt", "w+")
    for i in l:
        f.write(i+"\n")
    f.close()

ls = ["this", "is", "a", "sentence"]
newlines(ls)

This creates a new file if it doesn't exist and writes the contents of the list line by line.

Hope this helps!

Upvotes: 2

Related Questions