Working with File in Python
In this article, we will work with you to learn about file operations in Python. More specifically, how to open files, read files, write to files, close files, and methods to work with files you should know. Let's watch.
In this article, we will work with you to learn about file operations in Python. More specifically, how to open files, read files, write files, close files, and methods to work with files that you should know. Let's watch.
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
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:
MODE DESCRIPTION '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' để đọc
f = open("test.txt",'w') # mở file mode 'w' để ghi
f = 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ệp
f.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ệp
finally:
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("Quantrimangn")
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:
Quantrimang
Kiến thức - Kinh nghiệm - Hỏi đáp
TipsMake.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ên
print('Nội dung 11 kí tự đầu là:n', (a))
b = f.read(35) # đọc 35 kí tự tiếp theo
print('Nội dung 35 kí tự tiếp theo là:n', (b))
c = f.read() # đọc phần còn lại
print('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à:
Quantrimang
Nội dung 35 kí tự tiếp theo là:
Kiến thức - Kinh nghiệm - Hỏi đáp
Nộ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ên
print('Nội dung là: n', (a))
b = f.tell() # Kiểm tra vị trí hiện tại
print ('Vị trí hiện tại: ', (b))
f.seek(0) # Đặt lại vị trí con trỏ tại vị trí đầu file
c = f.read()
print('Nội dung mới là: n', (c))
Results returned:
Nội dung là:
Quantrimang
Vị trí hiện tại: 13
Nội dung mới là:
Quantrimang
Kiến thức - Kinh nghiệm - Hỏi đáp
TipsMake.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: Quantrimang
Nội dung dòng 2: Kiến thức - Kinh nghiệm - Hỏi đáp
Nộ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: Quantrimang
Nộ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 Quantrimang above.
The following table is a complete list of methods in the form of text, which you can refer to.
MODE DESCRIPTION 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.See more:
- Data type in Python
- Functions in Python
- Variable types in Python
Previous article: Matrix in Python
Next lesson: Managing files and folders in Python
You should read it
- Manage files and folders in Python
- How to Launch Python Files Using Windows Command Prompt
- Multiple choice quiz about Python - Part 3
- How to Open a Python File
- Function open () in Python
- How to batch rename files in Python
- More than 100 Python exercises have solutions (sample code)
- Module time in Python
- Bookmark 5 best Python programming learning websites
- Datetime in Python
- For in Python loop
- 5 choose the best Python IDE for you
Maybe you are interested
The chimpanzee speaks surprisingly human language This program will help you become invisible before the webcam lens is recording live Brain research explains the difference in the impact of technology on men and women What does the 'super slow' 7680fps movie recording feature on the Mate 30 Pro do? How to create slow motion videos on Android? How to reduce PDF file size by software