Python Basics: Files
Posted: Sun Jun 22, 2014 9:28 pm
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:
[*] '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:
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:
Writing
Writing to a file is as simple as calling the write function with a string argument, like so:
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:
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:
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:
To load a simple string, you can use the loads() function:
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:
json.dumps(), on the other hand, serializes an object and returns a string:
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;
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
The following modes can be used:f = open('filename', 'r+')
[*] '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
Readingf = open('binaryfilename', 'br+')
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
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:print(f.read()) #Reads and prints the whole file
print(f.read(5)) #Reads and prints 5 bytes of the file
Code: Select all
Similarily, readline() reads a single line of the file, but scans through it if you use it multiple times: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
Code: Select all
You can also use a for loop to iterate through the file:print(f.readline()) #Reads and prints the first line of the file
print(f.readline()) #Reads and prints the second line of the file
Code: Select all
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.for line in f:
print(line, end='')
Writing
Writing to a file is as simple as calling the write function with a string argument, like so:
Code: Select all
Closing a filef.write("This is the best file ever!")
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
Using JSONf.close()
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
Deserializingimport json
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
f is a file object that you would have created using the methods explained earlier.json_data = json.load(f)
To load a simple string, you can use the loads() function:
Code: Select all
Accessing the data is similar to accessing a list or dictionary:json_data = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
Code: Select all
Serializingprint(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
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
f is a file object that you've created using the methods explained earlier.json.dump(["foo", {"bar":["baz", None, 1.0, 2]}], f)
json.dumps(), on the other hand, serializes an object and returns a string:
Code: Select all
Notice that Python converts None to null. It'll also convert True to true and vice-versa.print(json.dumps(["foo", {"bar":["baz", None, 1.0, 2]}])) #Prints '["foo", {"bar": ["baz", null, 1.0, 2]}]'
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;