Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing a list to file function with filename and list as parameter

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading