Cs - Virginia.edu - File A Mode Using Print
Cs - Virginia.edu - File A Mode Using Print
Snapshot-Content-Location:
https://www.cs.virginia.edu/~up3f/cs1111/examples/file/write-file-a-mode-using-
print.txt
Subject:
Date: Thu, 13 Feb 2025 12:11:43 -0700
MIME-Version: 1.0
Content-Type: multipart/related;
type="text/html";
boundary="----MultipartBoundary--
HKWiV7npM2kNi7ZQQeCJw2jMbRH9eOVcwNCaiLRA2L----"
------MultipartBoundary--HKWiV7npM2kNi7ZQQeCJw2jMbRH9eOVcwNCaiLRA2L----
Content-Type: text/html
Content-ID: <[email protected]>
Content-Transfer-Encoding: binary
Content-Location: https://www.cs.virginia.edu/~up3f/cs1111/examples/file/write-
file-a-mode-using-print.txt
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)
######################################
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: # 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)
# 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
######################################
def write_to_file3(fname):
infile = open(fname, "r")
data = infile.read().split('\n')
outfile.close()
infile.close()
######################################
def write_to_file4(fname):
######################################
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 "a" (append mode),
# the cursor goes to the end of the file and
# append string to the file.
# Therefore, previously written lines remain.
</pre></body></html>
------MultipartBoundary--HKWiV7npM2kNi7ZQQeCJw2jMbRH9eOVcwNCaiLRA2L------