Files

The built-in function open() creates a Python file object, which serves as a link to a file residing on your machine. After calling open(), you can transfer strings of data to and from the associated external file by calling the returned file objects's methods.

Basic File Input/Output

This is the basic layout of creating a file. In this example, f is the file object from the builtin method open(). 'test.txt' is the name of the file we are creating and 'w' is the mode we are using (w = write).And finally we close the stream to the file with f.close().

In this example we are reading the previous example's file. We create the object f with open(). 'test.txt' is the file was are reading. This time there is no mode as open() without a mode default's to read, which you can put 'r' (r = read). f.read() takes in the entire file and assigns it to filer. Then we close the stream to the file and print the variable filer.

Modes

In the above example we used 'w' mode to write to the file. There are however different modes we can use. 'w' is write to. 'r' is read, which by having nothing as mode defaults to 'r'. 'a' is append to the file. 'rb' is read bytes. 'wb' is write bytes. Adding a '+' to either the input or output mode you can read and write to the same file object.

What data Type is the file?

In Python, it is always a string.

This example prints the output and type of data that the variable filer is, in which is:

So as you can see the the data type sent to and from the file is of type string. If you need an integer to compare to you can convert the string to int with the builtin int(), for example.

Reading specific parts of the file

file.readlines()

f.readlines() will read the entire file with each line as a index of a list. The first line being the first index and so on.

And the output. You can then if needed strip off the newline with the builtin function strip() upon iterating the list.

file.readline()

f.readline() will read the next line into the string including the newline character.

The output below shows each line being called along with its newline character which is why there is a blank space. Then after each line we have out regular print statement. The c is not printed after a newline because the thrid line in the file is the last line, which does not have a newline in it, thus there is not newline printed between the two.