16 Questions
Trong Python, hàm nào được sử dụng để mở một file?
open()
Phương thức nào đọc toàn bộ file vào một chuỗi?
read()
Chế độ nào được sử dụng để mở một file cho mục đích ghi?
w
Phương thức nào ghi một danh sách các chuỗi vào file?
writelines()
Chế độ nào được sử dụng để mở một file cho mục đích đọc và ghi?
Câu lệnh nào được sử dụng để mở một file và tự động đóng file khi hoàn thành?
with open()
Tác dụng của chế độ b là gì?
Đọc và ghi file nhị phân
Tác dụng của chế độ t là gì?
Đọc và ghi file văn bản
Context manager được sử dụng để làm gì?
Đảm bảo rằng tài nguyên được giải phóng sau khi sử dụng
Loại dữ liệu nào trong Python có thể chứa các giá trị thập phân?
float
Loại dữ liệu nào trong Python là một tập hợp các giá trị đã được sắp xếp?
list
Toán tử nào được sử dụng để thực hiện phân bổ giá trị đơn giản?
=
Tên biến trong Python có thể chứa các ký tự nào?
Chữ, số, dấu trừ và dấu chấm
Trong Python, câu lệnh nào được sử dụng để phân bổ nhiều giá trị cho nhiều biến?
x, y = 5, 10
Loại dữ liệu nào trong Python là một tập hợp các giá trị không được sắp xếp và không có giá trị trùng lặp?
set
Toán tử nào được sử dụng để thực hiện phân bổ giá trị tăng dần?
+=
Study Notes
File Input/Output in Python
Reading from a File
-
open()
function is used to open a file in Python -
open()
returns a file object, which has several methods for reading and writing -
read()
method reads the entire file as a string -
readlines()
method reads the entire file into a list of strings, where each string is a line in the file -
readline()
method reads a single line from the file
Writing to a File
-
open()
function is used to open a file in write mode by specifyingmode='w'
-
write()
method writes a string to the file -
writelines()
method writes a list of strings to the file
Modes
-
r
: opens a file for reading (default) -
w
: opens a file for writing, truncating the file first -
a
: opens a file for appending, adds to the end of the file -
x
: opens a file for exclusive creation, fails if the file already exists -
b
: binary mode, used for reading and writing binary files -
t
: text mode, used for reading and writing text files (default) -
+
: opens a file for updating (reading and writing)
Example Code
## Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
## Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, World!')
Context Manager
-
with
statement is used to open a file, which automatically closes the file when done - This is known as a context manager, which ensures that resources are released after use
Learn how to read and write files in Python, including different modes and the context manager. This quiz covers the basics of file input/output in Python.
Make Your Own Quizzes and Flashcards
Convert your notes into interactive study material.
Get started for free