Python Forum

Full Version: Function combining file manipulation and loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
good evening,
could I ask for some help with this assignment?

Quote:We want to save a list of words in a file so that we can reuse it later.

Define a function write_list_to_file(wordlst, filename) taking as parameters a list of words wordlst and a filename filename. The function should store the words in the list in a file (UTF8 encoding), one word per line.

so far I wrote:

wordlst=['walrus','cat','parrot','fish','monkey','giraffe'] #create a list of words

def write_list_to_file(wordlst, filename): #define function
    with open("filename.txt","w") as myfile: #the file doesn't exist, so it should create one, open in write mode
        for word in wordlst: #for element in wordlst
            myfile.write(word) #write element in myfile
        print(write_list_to_file(wordlst,filename)) #nothing happens


can you please point out my mistake? also I'd like to use \n somewhere to make sure to store one word per line,maybe on third line of the function?

thanks in adavance,
Leyo
Did you call the function?
(Mar-22-2022, 09:39 PM)deanhystad Wrote: [ -> ]Did you call the function?

hello,

when calling the function:
write_list_to_file(wordlst,myfile)
I get:
Error:
NameError Traceback (most recent call last) /tmp/ipykernel_6780/3840483989.py in <module> 6 myfile.write(word) #write element in myfile 7 print(write_list_to_file(wordlst,filename)) #nothing happens ----> 8 write_list_to_file(wordlst,myfile) 9 # votre code ici NameError: name 'myfile' is not defined
Hello,
You have to call the function with the name of the file as parameter.
wordlst = ['car', 'cat', 'dog']
write_list_to_file(wordlst, "filename.txt")
and modify your code like this:
def write_list_to_file(wordlst, filename): 
    with open(filename,"w") as myfile: 
        for word in wordlst: 
            myfile.write(word+"\n")
Quote of assignment doesn't mention loop. So alternative way could be to skip loop and use print (unpack list with*, set separator to newline, print to file) :

words =['walrus','cat','parrot','fish','monkey','giraffe']

def write_list_to_file(list_, filename):
    with open(filename, "w", encoding="UTF8") as f:
        print(*list_, sep='\n', file=f)

write_list_to_file(words, 'write_list_to_file.txt')
so simple...thank you Coricoco_fr!
thank you Perfringo, great to learn alternative ways to do this