Python file handling
Obtain file object
Open and close
1
2
3
4
5
6
7
8
9
10
11
12
13"""
Retrieves a file object on a certain mode
:param file: relative or basolute path to the file, including the extension
:type file: str
:param mode: a string that indicates what you want to do with the file
:type mode: str
:returns: a file object, with file-oriented API to an underlying resource
:rtype: obj
"""
my_file_object = open(file, mode)
# clean up
my_file_object.close()Mode Representation Read ("r")
Append ("a")
Write ("w")
Create ("x")
Text mode ("t")
Binary mode ("b")
Read + (over)write (r+)
or("w+")
Read + append ("a+")
- example
1
2
3
4# The relative path is "names.txt". Writing in bynary mode
open('dummy_file.txt', 'wb') # The relative path is "names.txt"
# Open file inside a folder
open('dummy_folder/dummy_file.txt')
- example
Read a file
Read
1
2
3my_file_object = open('dummy_folder/dummy_file.txt', 'r')
print(my_file_object.mode) # Output: 'r'
print(my_file_object.read()) # read returns a str- File object attributes:
name
: the name of the file.closed
: True if the file is closed. False otherwise.mode
: the mode used to open the file.
- File object attributes:
Readline
1
2
3
4
5
6
7
8
9
10
11""""
Reads one line of the file until it reaches the end of that line.
A trailing newline character (\n) is kept in the string.
:param size: optional, the maximum number of characters that you want to read.
:type size: int
:returns: one line of the file
:rtype: str
""""
file_object.readline(size)- example
1
2
3file_object = open('dummy_file.txt', 'r')
print(file_object.readline())
file_obejct.close()
- example
Readlines
1
2
3
4
5
6
7
8
9
10
11
12""""
Reads the file, and retrieves a list of string.
Each element of the list is a line of the file.
A trailing newline character (\n) is kept in the string.
:param size: optional, the maximum number of characters that you want to read.
:type size: int
:return: a list of strings, representing the whole file
:rtype: list
""""
file_object.readlines()- example
1
2
3
4
5file_object = open('dummy_file.txt', 'r')
# iterate on the list
for line in file_object.readlines():
print(line)
file_object.close()
- example
Create a file
You can create and write dynamically on it. If it already exists you will get an exception.
1 | file_object = open(filename, 'x') |
Write on a file
write
1
2
3
4
5
6
7
8
9
10
11
12""""
Writes on a file, either appending (mode 'a') or overwritting ('w')
:param my_new_content: the content you want to append
:type my_new_content: str
:param mode: the writting mode
:type mode: str
:return: the number of characters written
:rtype: int
""""
file_object.write(my_new_content, writting_mode)- example
1
2
3
4
5
6
7
8# append
file_object = open('dummy_file.txt', 'a')
file_object.write('\nthis a new line', )
file_object.close()
# overwrite
file_object = open('dummy_file.txt', 'w')
file_object.write('This is new content', )
file_object.close()
Delete a file
1 | import os |
Context manager
Structure which handles the files closing for you
1 | with open(file_name, file_mode) as file_object |
Handle exceptions
Exception | Cause |
---|---|
FileNotFoundError |
a file or directory is requested but doesn’t exist. |
PermissionError |
Trying to run an operation without the adequate access rights |
IsADirectoryError |
A file operation is requested on a directory |
- Try/catch
1
2
3
4
5
6try:
# Try to run this block of code
except <type_of_exception>:
# Python stops the process and jumps to this block
finally
# Do this after running the code, even if an exception was raised- example
1
2
3
4
5
6try:
f = open('names.txt')
except FileNotFoundError:
print('The file does not exist')
finally:
f.close()
- example