Python provides the basic functions and methods needed to manipulate files. This article I would like to introduce the most basic operations with files in Python.
1. Open File
Before working with any file, you must open it. To open a file, Python provides the open()
function. It returns a file object that is used with other functions. With the file open, you can perform operations such as reading, writing new, writing more … on that file.
– Syntax:
file object = open(file_name [, access_mode][, buffering])
Inside:
-
filename
: The file_name argument is a string value containing the names of the files you want to access. -
access_mode
: The access_mode determines the mode of the file to be opened such as read, write, append, … This is an optional parameter and the default file access mode is read (r). -
buffering
: If the buffer is set to 0, that means no buffers will take place. If specified as 1, then the stream buffer is executed while accessing a File. If the integer is greater than 1, then the buffer operation is performed with the given buffer size. If it is negative, the buffer size will be the default.
Here is a list of the different modes of opening a file:
Mode | Description |
---|---|
r | Open file for reading only |
r + | Open file for reading and writing |
rb | Open the file in read mode for binary format, this is the default mode. The cursor at the beginning of the file |
rb + | Open file for reading and writing in binary format. The cursor at the beginning of the file |
w | Create a new file to burn, if the file already exists, the new file will be written |
w + | Create a new file to read and write, if the file exists, it will be written new |
wb | Open the file in write mode in binary format. If the file already exists, then overwrite its contents, otherwise create a new file |
wb + | Open file for reading and writing in binary format. If the file exists, overwrite its contents; if the file does not exist, create a new file to read and write |
a | Open the file to write at the end of the file, if it is not found, it will create a new file to write |
a + | Open the file to read and write to the end of the file, if it is not found, it will create a new file to read and write |
ab | Open the file in append mode in binary mode. The cursor is at the end of the file if the file already exists. If the file does not exist, create a new file for writing |
ab + | Open internal file for reading and append in binary format. File pointer at the end if the file already exists. If it doesn't exist, create a new file to read and write |
– File properties
Properties | Description |
---|---|
file.closed | Returns True if the file is closed, otherwise False |
file.mode | Returns the access mode of the file being opened |
file.name | Returns the name of the file |
– For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/python # Mở file file = open("plc.txt", "wb") print "Tên của file là: ", file.name print "File có đóng hoặc không? : ", file.closed print "Chế độ mở file : ", file.mode |
Results displayed on the screen:
1 2 3 4 5 | Tên của file là: plc.txt File có đóng hoặc không? : False Chế độ mở file : wb |
2. Close File
When you are done with the file operations, you need to close the file. Python automatically closes a file when the reference object of one file has been reassigned to another file. However, using the close()
to close a file is still better.
** – Syntax: **
fileObject.close()
** – For example:**
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/python # Mở file file = open("plc.txt", "r") # Đóng file file.close() |
3. Read File
Suppose we have a vidu.txt
file with the following content:
1 2 3 | Hello all! My name's Phuc. |
3.1. Read method
– Syntax:
fileObject.read([size])
This method returns a string of size equal to size
. If size
is not passed, the entire contents of the file will be read.
**- For example: **
1 2 3 4 5 6 7 | #!/usr/bin/python f = open('vidu.txt', 'r') str= f.read() print ('Noi dung file la:n', str) |
Print result to screen:
1 2 3 4 5 | Noi dung file la: Hello all! My name's Phuc. |
3.2. Readline method
– Syntax:
fileObject.readline()
This method allows reading a line in the file and returning the string.
** – For example: **
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/python f = open('vidu.txt', 'r') line1 = f.readline() line2 = f.readline() print ('Dòng 1: ', line1) print ('Dòng 2: ', line2) |
Print result to screen:
1 2 3 4 5 | Dòng 1: Hello all! Dòng 2: My name's Phuc. |
4. Write File
Similar to reading a file, to write a file we need to open the file with the syntax to write and use the write
method to write
to.
**- Syntax: **
fileObject.write(string)
This method allows you to write a string with the content of the string in the position of the cursor in the file.
** – For example: **
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/python # Mở file file = open("plc.txt", "wb") file.write( "Python là ngôn ngữ tốt nhất"); # Đóng file file.close() |
And the following is the content inside plc.txt
file after performing successful file writing.
1 | Python là ngôn ngữ tốt nhất |
5. Rename File
The rename()
in the os
module is used to rename files. This method takes two parameters: old file name and new file name.
– Syntax:
os.rename("<tên file hiện tại>", "<tên file mới>")
– For example:
1 2 3 4 5 6 7 | import os #Thay tên plc1.txt thành plc2.txt: os.rename( "plc1.txt", "plc2.txt" ) |
6. Delete File
You can use the remove()
of the os module to delete files whose parameters are the names of the files you need to delete.
– Syntax:
os.remove("<tên file>")
**- For example: **
1 2 3 4 5 6 7 | import os # Xóa plc2.txt os.remove("plc2.txt") |
7. File location
The tell()
will tell you the current position inside the file. In other words, the next read and write will take place on those bytes.
The seek(offset[, from])
changes the current position inside the file.
- The
offset
parameter is the number of bytes to be moved. - The
from
parameter determines the reference location from which the byte is moved.- If
from
is 0, use the file header as the reference position - If
from
is 2, use the end of the file as the reference position.
- If
** For example: **
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # Mở file file = open("plc.txt", "r+") str = file.read(10); print "Chuỗi đã đọc là: ", str # Kiểm tra con trỏ hiện tại vitri = file.tell(); print "Con trỏ hiện tại: ", vitri # Đặt lại vị trí con trỏ tại vị trí đầu file vitri = file.seek(0, 0); str = file.read(10); print "Chuỗi đã đọc là : ", str # Đóng file file.close() |
The results appear on the screen as follows:
1 2 3 4 5 | Chuỗi đã đọc là : Python là Con trỏ hiện tại : 10 Chuỗi đã đọc là : Python là |
8. Reference
Besides reading and writing files, there are many other operations to handle files. You can learn more about file handling practices in other python here: