Home > Mobile >  Writing a list to file function with filename and list as parameter
Writing a list to file function with filename and list as parameter

Time:04-14

I'm trying to write a function such as the one below except it it'd take the list and filename as parameter. It's annoyingly basic and yet it escapes me.

def write_list_to_file():
    wordlst = ["No", "Time", "for", "this"]
    file = open(filename, 'w')
    for items in wordlst:
        file.writelines(items   '\n')
    file.close()wordlst

Given that this works, this:

def write_list_to_file(wordlst, filename):
    wordlst = ["No", "Time", "for", "this"]
    with open(filename ".txt",'w') as file:
        for items in wordlst:
            file.writelines(items   '\n')

Should too. Except that calling the function in the fashion of write_list_to_file(wordlst, Idk) returns no file. Fully aware that the list remains static i've tried a single paramater function in the same fashion, I.e :

def makefile(filename):
    file = open(filename   ".txt", 'w')
    file.close()

makefile("Really")

This yields no file either somehow. Please do ignore the list's elements, i've been on this a lot longer than i care to admit and i couldn't find something that helps solve this particular issue. I've found countless solutions to make this happen, but not in the shape of a function taking any list and any file as input. In every case the exit code shows no error, so i'd at least expect a file to be create yet cant find any.

TLDR: tryin to make a write_list_to_file(wordlst,filename) function, must be missing stupidly obvious, help appreciated.

Edit: approved, the indention issue was only in this post though, the code was indented properly, made this in a hurry

Edit2: cf comments

CodePudding user response:

Your code examples do not have the right indentation, which is important when writing python code.

Futhermore, writelines() takes in a list of strings. You iterate through your list and want to save each element on a seperate line - write() would be the right function for that.

Last, make sure to pass your filename as a string.

This code should work:

def write_list_to_file(wordlst, filename):
    with open(filename   '.txt', 'w') as file:
        for item in wordlst:
            file.write(item   '\n')

write_list_to_file(['element1', 'element2', 'element3'], 'tempfile')
  • Related