File handling
Writing files
# open() opens a file and returns the address of the object
# To be able to write to a file, the second
# argument should be w.
even_file = open("even.txt", "w")
odd_file = open("odd.txt","w")
# Opening file in write mode
# Creates a file if it isn't present.
# If a file is present, it gets overwritten and data is lost.
# write mode doesn't allow the file to be read.
for i in range(100):
if i % 2 == 0:
# All IO operations happen via strings.
# so argument of write should be passed a string.
even_file.write(str(i))
even_file.write("\n")
else:
odd_file.write(str(i))
odd_file.write("\n")
# A file should always be closed
# to free system resources.
even_file.close()
odd_file.close()Reading files
The case of the new line.
List comprehension
Examples:
Appending files
Binary Mode
Other methods
Exercise
Last updated