Python Basics: Files

1 post Page 1 of 1
Contributors
User avatar
comathi
Coding God
Coding God
Posts: 1242
Joined: Fri Mar 26, 2010 1:59 pm

Python Basics: Files
comathi
Hello guys, today I'll be filling the Python tutorials section a bit more by talking about file operations (ie, reading and writing to or from a file). I'll also explain how you can use JSON to produce or parse structured data files.

I should also probably mention that this tutorial is written for Python 3.x. If you have an earlier (or later) version of Python, it's probably best to check with the official documentation to make sure the code still works. You can find it here: https://docs.python.org/3.3/tutorial/index.html

Having gone over the technicalities, let's get started, shall we? ;)

The file object
As is custom in Python, most everything is an object. Files are no exception. There are two main types of file objects in Python: text files and binary files. Both of which use the same common functions for reading and writing.

The usual way of creating a file object in Python is by using the open function. This can take two arguments: a filename, and optionally, a mode. Opening a file usually looks something like this:
Code: Select all
f = open('filename', 'r+')
The following modes can be used:

[*] 'r' read-only (default mode)
[*] 'w' write-only
[*] 'a' append
[*] 'r+' read/write

If you wish to open a file in binary mode, you can append 'b' to the mode, like so:
Code: Select all
f = open('binaryfilename', 'br+')
Reading
Once you have a file object, reading it is as easy as using one of two following functions: read() and readline().

read() can take an optional size parameter, which corresponds to the number of bytes you want to read from the file. If you omit the size (or enter a negative size), it'll read and return the whole file:
Code: Select all
print(f.read()) #Reads and prints the whole file
print(f.read(5)) #Reads and prints 5 bytes of the file
If you use the read() function more than once on the same file, it'll simply scan through until it reaches the end, at which point it'll return an empty string:
Code: Select all
print(f.read(5)) #Reads and prints the first 5 bytes of the file
print(f.read(5)) #Reads the prints the next 5 bytes of the file
Similarily, readline() reads a single line of the file, but scans through it if you use it multiple times:
Code: Select all
print(f.readline()) #Reads and prints the first line of the file
print(f.readline()) #Reads and prints the second line of the file
You can also use a for loop to iterate through the file:
Code: Select all
for line in f:
    print(line, end='')
The reason I used the end='' arguments is because by default, Python adds a "\n" newline character at the end of each line. Specifying the line ending allows us to print each line one after the other, without an extra new line between two consecutive lines.

Writing

Writing to a file is as simple as calling the write function with a string argument, like so:
Code: Select all
f.write("This is the best file ever!")
Closing a file

Once you're done using a file, always remember to close it. This ensures all data is written or read properly and avoids corrupting a file or losing data:
Code: Select all
f.close()
Using JSON

Now that you can use files, I'll show you how to use JSON to create and read structured data files. Python includes a very handy json module in its standard library that handles such files, so all you have to do is import it:
Code: Select all
import json
Deserializing

The first thing we'll see is how to load a JSON file or string and decode it.

To deserialize a JSON file, use the load() function:
Code: Select all
json_data = json.load(f)
f is a file object that you would have created using the methods explained earlier.

To load a simple string, you can use the loads() function:
Code: Select all
json_data = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
Accessing the data is similar to accessing a list or dictionary:
Code: Select all
print(json_data[0]) #Prints "foo"
print(json_data[1]['bar']) #Prints ["baz", null, 1.0, 2]
print(json_data[1]['bar'][2]) #Prints 1.0
Serializing

Again, there are two ways of writing JSON data to a file: json.dump() and json.dumps()

json.dump writes JSON data to a file, like so:
Code: Select all
json.dump(["foo", {"bar":["baz", None, 1.0, 2]}], f)
f is a file object that you've created using the methods explained earlier.

json.dumps(), on the other hand, serializes an object and returns a string:
Code: Select all
print(json.dumps(["foo", {"bar":["baz", None, 1.0, 2]}])) #Prints '["foo", {"bar": ["baz", null, 1.0, 2]}]'
Notice that Python converts None to null. It'll also convert True to true and vice-versa.

That's all you have to know to start using files in Python. I hope you enjoyed this tutorial, there's hopefully plenty more to come cooll;
1 post Page 1 of 1
Return to “Tutorials”