File Writing

File Handles

  • Provide an interface to work with an open file
  • Common operations include reading, writing, and closing

Reading

  • Open a file with default file mode (read)
  • Use the read method to move text content from the file to a string

Example

pyfile = open("example.py")

source = pyfile.read()

print(source)

Writing

  • Open a file with mode set to “w”
  • Use the write method to write to the file

Example

outfile = open("myfile.txt", "w")

outfile.write("Hello, world")

outfile.close()

Closing

  • Files must be properly closed to ensure all data is correctly written

Example

outfile = open("myfile.txt", "w")

outfile.write("Hello, world")

Truncation

  • When a file is opened for writing, it is truncated by default
  • This means all existing content will be destroyed

Appending

  • Files can be opened for appending using the “a” flag

Example

outfile = open("myfile.txt", "a")

outfile.write("Hello, world")

outfile.close()

Exceptions

  • An exception crashing the program can prevent a proper close

Example

outfile = open("myfile.txt", "a")

outfile.write("Hello, world")

int("not a number")

outfile.close()

Closing Files

  • It is important to close files when we finish using them
  • It can be easy to forget to do this
  • with can be used to automatically close a file

Example

with open("myfile.txt", "w") as outfile:
    outfile.write("Hello, world")

with

  • The with statement can be used with all context manager types
  • File handles are one use, but there are many others
  • with always closes the file, even when exceptions are raised

Exercise

Write the first 1000 positive integers to a file

Exercise

Read the values from that file one at a time and write their squares to a second file

Solution

with open("nums.txt") as nums:
    with open("squares.txt", "w") as squares:
        for num in nums:
            square = int(num) * int(num)
            squares.write(f"{square}\n")

Key Ideas

  • Files can be opened with the “w” flag
  • We can avoid truncation with the “a” flag
  • The with statement can be used to automatically close files