Working with File in Python

Tram Ho

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:

Results displayed on the screen:

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:**

3. Read File

Suppose we have a vidu.txt file with the following content:

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: **

Print result to screen:

3.2. Readline method

– Syntax:

fileObject.readline()

This method allows reading a line in the file and returning the string.

** – For example: **

Print result to screen:

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: **

And the following is the content inside plc.txt file after performing successful file writing.

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:

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: **

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.

** For example: **

The results appear on the screen as follows:

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:

Share the news now

Source : Techtalk