# Write a function that read data from todo.csv # and write the data to output.txt file def write_to_file1(fname): # infile = None # for input file (if we want to create a variable before opening a file) # outfile = None # for output file infile = open(fname, "r") # open file to be read in # Read the entire file, then split lines, resulting in a list of lines data = infile.read().split('\n') # print(data) # let's see what we read from the file (print in console) outfile = open('output-w-write-1.txt', 'w') # open file to be written out # Write to file, using write(string_to_be_written), # pass in string (content) to be written (note: *must* be string), outfile.write(str(data)) # Since we open the files, using open(), be sure to close them outfile.close() infile.close() ###################################### def write_to_file2(fname): # open file to be read in, and assign it to a variable named infile with open(fname, "r") as infile: # Read the entire file, then split lines, resulting in a list of lines data = infile.read().split('\n') # print(data) # The infile file is automatically closed when the execution # of the with open block is completed. # Therefore, no need to call .close() # note: *must* indent all the code related to this file # open file to be written out, and assign it to a variable named outfile with open('output-w-write-2.txt', 'w') as outfile: # Write to file, using write(string_to_be_written), # pass in string (content) to be written (note: *must* be string), outfile.write(str(data)) # The outfile file is automatically closed when the execution # of the with open block is completed. # Therefore, no need to call .close() # note: *must* indent all the code related to this file ###################################### def write_to_file3(fname): infile = open(fname, "r") data = infile.read().split('\n') outfile = open('output-w-write-3.txt', 'w') for line in data: outfile.write(line + '\n') # Unlike print(), write() does not insert new line. # To format the output file line by line, # we must explicitly include the new line character ('\n') outfile.close() infile.close() ###################################### def write_to_file4(fname): with open(fname, "r") as infile: data = infile.read().split('\n') with open('output-w-write-4.txt', 'w') as outfile: for line in data: outfile.write(line + '\n') # Unlike print(), write() does not insert new line. # To format the output file line by line, # we must explicitly include the new line character ('\n') ###################################### write_to_file1("todo.csv") write_to_file2("todo.csv") write_to_file3("todo.csv") write_to_file4("todo.csv") # This version will reopen the output file for each line # Because of the "w" (write mode), the line previously written in the file # was wiped off as the cursor goes back to the beginning of the file.