Files

File handling is fairly simple in Python, as many pre-existing components of the language can be used to interface with external files present in a filesystem.

Say our file "foobar" contains these lines:

foo
bar

You can open the "foobar" file like so::

open_file = open("foobar")

And print its contents out like so:

for line in open_file:
   print(line, end="")
foo
bar

Which means that the file can be treated as if it is a list of strings, containing each line in the file.

print("".join(open_file))
foo
bar

While a file object is not mutable the same way a list is, an open file can be modified if the write flag is enabled.

If you want to write to a file, it must be opened with a writable 'mode'. To add to the end of a pre-existing file, use the 'a' flag.

open_file_out = open("foobar", 'a')

File Opening Codes

  • r
    • read file, error if doesn't exist
  • w
    • write, create if doesn't exist, overwrite if file exists
  • w+
    • write or read, overwrite file if it exists
  • r+
    • read or write, starting from top of existing file
  • a
    • append to end of file, create if doesn't exist
  • a+
    • append or read, create if doesn't exist
  • x
    • write, error if file already exists

And to each of these, options can be added modifiers:

  • t
    • read as ascii text
  • b
    • read as binary (everything that isn't ascii text, more or less)

If we want to create a new file which contains non-text data, something like following would work.

new_file = open("exec", "xb")

The default value is 'rt'. File objects are written to the same ways regardless of what mode they are opened with.

With the file.write() method:

open_file_out.write("\n123\n345\n")

Because the file is opened with the a flag, the string will be written to the end of the file, and the original file contents will not be overwritten.

print("Words", file=open_file_out)

print() contains a named argument 'file' which can be used to specify what file will be printed to. The default is (effectively, not literally) stdout, which is usually the display terminal interface the script is currently being run on.

Ways to write multiple lines to a file sequentially without a loop:

lines = ["one", "two", "three"]

File.writelines() function:

open_file_out.writelines(lines)

Alternatively, print()

print('\n', *lines, end="\n", sep="", file=open_file_out) 
# recall that *<listname> expands a list as if it were separated by commas

A file won't actually be written to until it is closed, so close() must be used.

open_file_out.close()

Now, to read it:

open_file = open("foobar", "r")
print(*open_file, sep='', end='')
open_file.close()
foo
bar
123
345
Words
onetwothree
onetwothree

And to reset it to what it was before running all this code:

open_file = open("foobar", "w")
open_file.writelines(["foo\n", "bar"])
open_file.close()