File_Handling
File_Handling
– File Handling
∗ Opening Files for Reading
∗ Opening Files for Writing and Updating
∗ Deleting Files
– File Types
∗ File with txt Extension
∗ File with json Extension
∗ Changing JSON to Dictionary
∗ Changing Dictionary to JSON
∗ Saving as JSON File
∗ File with csv Extension
∗ File with xlsx Extension
∗ File with xml Extension
Chapter 13
File Handling
So far we have seen different Python data types. We usually store our data
in different file formats. In addition to handling files, we will also see different
file formats(.txt, .json, .xml, .csv, .tsv, .excel) in this section. First, let us get
familiar with handling files with common file format(.txt).
File handling is an import part of programming which allows us to create, read,
update and delete files. In Python to handle data we use open() built-in function.
# Syntax
open('filename', mode) # mode(r, a, w, x, t,b) could be to read, write, update
• “r” - Read - Default value. Opens a file for reading, it returns an error if
the file does not exist
• “a” - Append - Opens a file for appending, creates the file if it does not
exist
• “w” - Write - Opens a file for writing, creates the file if it does not exist
• “x” - Create - Creates the specified file, returns an error if the file exists
• “t” - Text - Default value. Text mode
• “b” - Binary - Binary mode (e.g. images)
1
As you can see in the example above, I printed the opened file and it gave some
information about it. Opened file has different reading methods: read(), readline,
readlines. An opened file has to be closed with close() method.
• read(): read the whole text as string. If we want to limit the number of
characters we want to read, we can limit it by passing int value to the
read(number) method.
f = open('./files/reading_file_example.txt')
txt = f.read()
print(type(txt))
print(txt)
f.close()
# output
<class 'str'>
This is an example to show how to open a file and read.
This is the second line of the text.
Instead of printing all the text, let us print the first 10 characters of the text file.
f = open('./files/reading_file_example.txt')
txt = f.read(10)
print(type(txt))
print(txt)
f.close()
# output
<class 'str'>
This is an
• readline(): read only the first line
f = open('./files/reading_file_example.txt')
line = f.readline()
print(type(line))
print(line)
f.close()
# output
<class 'str'>
This is an example to show how to open a file and read.
• readlines(): read all the text line by line and returns a list of lines
f = open('./files/reading_file_example.txt')
lines = f.readlines()
print(type(lines))
print(lines)
f.close()
2
# output
<class 'list'>
['This is an example to show how to open a file and read.\n', 'This is the second line of th
Another way to get all the lines as a list is using splitlines():
f = open('./files/reading_file_example.txt')
lines = f.read().splitlines()
print(type(lines))
print(lines)
f.close()
# output
<class 'list'>
['This is an example to show how to open a file and read.', 'This is the second line of the
After we open a file, we should close it. There is a high tendency of forgetting
to close them. There is a new way of opening files using with - closes the files by
itself. Let us rewrite the the previous example with the with method:
with open('./files/reading_file_example.txt') as f:
lines = f.read().splitlines()
print(type(lines))
print(lines)
# output
<class 'list'>
['This is an example to show how to open a file and read.', 'This is the second line of the
3
Deleting Files
We have seen in previous section, how to make and remove a directory using os
module. Again now, if we want to remove a file we use os module.
import os
os.remove('./files/example.txt')
If the file does not exist, the remove method will raise an error, so it is good to
use a condition like this:
import os
if os.path.exists('./files/example.txt'):
os.remove('./files/example.txt')
else:
print('The file does not exist')
File Types
File with txt Extension
File with txt extension is a very common form of data and we have covered it in
the previous section. Let us move to the JSON file
# we use three quotes and make it multiple line to make it more readable
person_json = '''{
"name":"Asabeneh",
"country":"Finland",
"city":"Helsinki",
"skills":["JavaScrip", "React","Python"]
}'''
4
Changing JSON to Dictionary
To change a JSON to a dictionary, first we import the json module and then we
use loads method.
import json
# JSON
person_json = '''{
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"skills": ["JavaScrip", "React", "Python"]
}'''
# let's change JSON to dictionary
person_dct = json.loads(person_json)
print(type(person_dct))
print(person_dct)
print(person_dct['name'])
# output
<class 'dict'>
{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills': ['JavaScrip', 'Reac
Asabeneh
5
"city": "Helsinki",
"skills": [
"JavaScrip",
"React",
"Python"
]
}
6
else:
print(
f'\t{row[0]} is a teachers. He lives in {row[1]}, {row[2]}.')
line_count += 1
print(f'Number of lines: {line_count}')
# output:
Column names are :name, country, city, skills
Asabeneh is a teacher. He lives in Finland, Helsinki.
Number of lines: 2
7
# output
Root tag: person
Attribute: {'gender': 'male'}
field: name
field: country
field: city
field: skills