# 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-print-1.txt', 'w') # open file to be written out # Write to file, using print, # pass in content to be written, # specify the file to be written to print(data, file=outfile) # 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-print-2.txt', 'w') as outfile: # Write to file, using print, # pass in content to be written, # specify the file to be written to print(data, file=outfile) # 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-print-3.txt', 'w') for line in data: print(line, file=outfile) outfile.close() infile.close() ###################################### def write_to_file4(fname): with open(fname, "r") as infile: data = infile.read().split('\n') with open('output-w-print-4.txt', 'w') as outfile: for line in data: # print(line, file=outfile) outfile.write(line + '\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.