Table of Contents
This guide covers working with file in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
What Is the File?
File also known as file, file. File is a collection of information that is named and stored on computer memory such as hard disk, floppy disk, CD, DVD, .
When you want to read or write files, we need to open the file first. When completed, the file needs to be closed so that the resources associated with the file are released.
Therefore, in Python, a file operation takes place in the following order.
- Open the file
- Read or write
- Close the file
How to Open File in Python
In Python, there is a built-in function for opening the file: Open (). This function returns a file object called 'handle' because you can perform read, write, modify operations on that file.
>>> f = open("test.txt") # m? file cùng th? m?c v?i file hi?n t?i>>> f = open("C:/Python33/README.txt") # m? file ? th? m?c khác, ???ng d?n ??y ??
You can determine how the file is opened to do things like read, write, append, . This is an optional parameter that may or may not be. You can also specify the file to open in text or binary format.
The default file access mode is read (r). When using this mode we will get the string value returned as text.
On the other hand, if the return value is in bytes, the file is opened as an image or an exe.
Below is a list of different mode modes when opening a file:
MODEDESCRIPTION 'r' Mode is only readable. 'r +' Mode is allowed to read and write 'rb' Open the read mode file for binary format. Cursor at the beginning of the file 'rb +' 'r + b' Open the file to read and write in binary format. Cursor at the beginning of the file 'w' Open the file to write. If the file does not exist, it will create a new file and write the content, if the file already exists, it will be truncated and overwrite the old content 'w +' Open the file to read and write. If the file does not exist, it will create a new file and write the content, if the file already exists, it will be truncated and overwrite the old content 'wb' Open the file to write to binary. If the file does not exist, it will create a new file and write the content. If the file already exists, it will be truncated and overwrite the old content 'wb +'. 'w + b' Open the file to read and write to binary. If the file does not exist, it will create a new file and write the content. If the file already exists, it will be truncated and overwrite the old content. If the file already exists, it will write the content to the end of the file, if the file does not exist then create a new file and write the content there. 'a +' Open the read and write mode files. If the file already exists, it will write the content to the end of the file, if the file does not exist then create a new file and write the content there. 'ab', Open the recording mode file in binary format. If the file already exists, it will write the content to the end of the file, if the file does not exist then create a new file and write the content there. 'ab +' 'a + b Open the read and write mode files in binary form. If the file already exists, it will write the content to the end of the file, if the file does not exist then create a new file and write the content there. 'x' Open the recording mode file. Create new exclusive file and write the content, if the file already exists, the program will report 'x +' error Open the read and write mode file. Create new exclusive file and write the content, if the file already exists, the program will report 'xb' error. Open binary file mode. Create new proprietary file and write the content, if the file already exists, the program will report 'xb +' error 'x + b' Open the read and write file in binary format. Create a new proprietary file and write the content, if the file already exists, the program will issue an error 'b' Open the file in binary mode 't' Open the file in text mode (default)
f = open("test.txt") # m? file mode 'r' ho?c 'rt' ?? ??cf = open("test.txt",'w') # m? file mode 'w' ?? ghif = open("img.bmp",'r+b') # m? file mode 'r+b' ?? ??c và ghi d?ng nh? phân
When working with files in text mode, you should specify the encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')
Close File in Python
After you have done the file operations, you need to close it.
Close the file to ensure the opening and closing rules for the program, so this is necessary.
Closing the file is built in Python using the Close () Function .
Python also automatically closes a file when the reference object of the file has been re-assigned to another file. However, it is better to use the Close () method To close a file.
f = open("test.txt",encoding = 'utf-8')# th?c hi?n các thao tác v?i t?pf.close()
However, this method is not really guaranteed. There are cases where some exceptions occur when we perform operations with the file that cause the program to automatically exit without closing the file.
To be more secure, you should use the try. Finally block (finally will always be executed regardless of whether or not exceptions) here.
try:f = open("test.txt",encoding = 'utf-8')# th?c hi?n các thao tác v?i t?pfinally:f.close()
In this way, we can be assured that the file is closed properly even when an exception is raised that makes the program stop unexpectedly.
Another way to close the file is to use the With Command . The With Command tells us that the file is always closed without knowing the internal processing logic.
with open("test.txt",encoding = 'utf-8') as f:# th?c hi?n các thao tác v?i t?p
Comparing these two methods, we have seen very clearly that using With Gives us a way to write more concise code.
Remember File in Python
To write a file we need to open the file with the syntax to write, use write mode 'w', append 'a' or exclusive creation mode 'x'
You need to be careful with the 'w' mode, because it overwrites the content if the file already exists, the previous data will be deleted.
If you write to a binary file with byte strings or text, the result will be the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f:f.write("Tipsmaken")f.write("Ki?n th?c - Kinh nghi?m - H?i ?ápnn")f.write("TipsMake.comn")
With the above example, the program will create a file named Test. Txt If the file does not exist yet, if it exists, it will be overwritten.
Use the 'n' characters To distinguish lines.
The result returned is:
TipsmakeKi?n th?c - Kinh nghi?m - H?i ?ápTipsMake.com
Read File in Python
Similar to file writing, to read a file we need to open the file with the syntax to read, using read 'r' mode.
Use read (size)
Use Read (size) method To retrieve data with size equal to size. If this parameter is left blank, it will read the file or if the file is too large, it will read until the limit of memory allows.
f = open("test.txt",'r',encoding = 'utf-8')a = f.read(12) # ??c 12 kí t? ??u tiênprint('N?i dung 11 kí t? ??u là:n', (a))b = f.read(35) # ??c 35 kí t? ti?p theoprint('N?i dung 35 kí t? ti?p theo là:n', (b))c = f.read() # ??c ph?n còn l?iprint('N?i dung ph?n còn l?i là:n', (c))
Run the program, the result is:
N?i dung 12 kí t? ??u là:TipsmakeN?i dung 35 kí t? ti?p theo là:Ki?n th?c - Kinh nghi?m - H?i ?ápN?i dung ph?n còn l?i là:TipsMake.com
Use tell () and seek ()
In addition, we have a Tell () Method that tells you the current location inside the file. In other words, the next read and write will continue on those bytes.
The Seek () method Changes the current position within the file.
f = open("test.txt",'r',encoding = 'utf-8')a = f.read(12) # ??c 12 kí t? ??u tiênprint('N?i dung là: n', (a))b = f.tell() # Ki?m tra v? trí hi?n t?iprint ('V? trí hi?n t?i: ', (b))f.seek(0) # ??t l?i v? trí con tr? t?i v? trí ??u filec = f.read()print('N?i dung m?i là: n', (c))
Results returned:
N?i dung là:TipsmakeV? trí hi?n t?i: 13N?i dung m?i là:TipsmakeKi?n th?c - Kinh nghi?m - H?i ?ápTipsMake.com
Use readline ()
This method allows reading each line in the file:
f = open("test.txt",'r',encoding = 'utf-8')a = f.readline()print ('N?i dung dòng ??u: ', (a))b = f.readline()print ('N?i dung dòng 2: ', (b))c = f.readline()print ('N?i dung dòng 3: ', (c))d = f.readline()print ('N?i dung dòng 4: ', (d))
Print results to the screen:
N?i dung dòng ??u: TipsmakeN?i dung dòng 2: Ki?n th?c - Kinh nghi?m - H?i ?ápN?i dung dòng 3:N?i dung dòng 4: TipsMake.com
Use readlines ()
The Readlines () method Returns all the remaining lines in the file and returns the empty value at the end of the file.
f = open("test.txt",'r',encoding = 'utf-8')a = f.readline()print ('N?i dung dòng ??u: ', (a))b = f.readlines()print ('N?i dung các dòng còn l?i: n', (b))c = f.readlines()print ('N?i dung các dòng còn l?i: n', (c))
Results displayed on the screen:
N?i dung dòng ??u: TipsmakeN?i dung các dòng còn l?i:['Ki?n th?c - Kinh nghi?m - H?i ?ápn', 'n', 'TipsMake.comn']N?i dung các dòng còn l?i:[]
Some Methods Work with File in Python
There are many different methods to work with Python's built-in files, some of which have been explored by TipsMake above.
The following table is a complete list of methods in the form of text, which you can refer to.
MODEDESCRIPTION Close () Close an open file. It cannot be executed if the file is closed. Fileno () Returns an integer file descriptor (file descriptor). Flush () Clean the file stream's cache. Isatty () Returns TRUE if the file is connected to a terminal. Read (n) Read n characters in the file. Readable () Returns TRUE if the file is readable. Readline (n = -1) Read and return a line from the file. Read at most n bytes / characters if specified. Readlines (n = -1) Read and return a list of lines from the file. Read at most n bytes / characters if specified. Seek (offset, from = SEEK_SET) Change the current position inside the file. Seekable () Returns TRUE if the stream supports random access. Tell () Returns the current position inside the file. Truncate (size = None) Cut file size to size parameter size. Writable () Returns TRUE if the file is writable. Write (s) Write s characters into the file and return. Writelines (lines) Writes a list of lines and files.
Previous article: Matrix in Python
Next lesson: Managing files and folders in Python
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.