Python Forum
Function combining file manipulation and loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function combining file manipulation and loop
#1
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
Reply


Messages In This Thread
Function combining file manipulation and loop - by Leyo - Mar-22-2022, 08:50 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I run a function inside a loop every 24 values of the loop iteration range? mcva 1 2,201 Sep-18-2019, 04:50 PM
Last Post: buran
  help! function that checks if a file is a bed file, tips so i can code it myself lilyS 1 2,458 May-31-2019, 12:41 PM
Last Post: ichabod801
  While loop within a Function (2.7) tuffgong 3 3,602 Jun-28-2017, 05:54 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020