Trường ĐH Công nghệ – Đại học Quốc gia Hà Nội
Trước đây, chương trình chỉ xử lý một lần chạy:
name = input("What's your name?")
print(f"hello, {name}")
Nếu nhập nhiều lần (ví dụ 3 lần):
for _ in range(3):
name = input("What's your name?")
print(name)
Cần lưu 3 tên vào một list:
names = []
for _ in range(3):
names.append(input("Give me your name:"))
⚠️ Lưu ý Windows: dấu \ là ký tự escape trong Python → ưu tiên / hoặc raw string r"...".
Python cung cấp giao diện đơn giản để làm việc với tệp:
| Hàm | Ý nghĩa |
|---|---|
| open | Mở tệp, tạo file handle |
| close | Đóng tệp, giải phóng tài nguyên |
| read | Đọc dữ liệu từ tệp vào chương trình |
| write | Ghi dữ liệu từ chương trình ra tệp |
file = open('filename.txt','mode')
| Mode | Ý nghĩa | Hành vi |
|---|---|---|
| r | Read | ❌ Nếu sai đường dẫn / không tồn tại → FileNotFoundError |
| w | Write | ✅ Tạo mới nếu chưa có; ⚠️ ghi đè nếu đã tồn tại |
| a | Append | ✅ Tạo mới nếu chưa có; ✅ ghi thêm vào cuối tệp |
⚠️ Còn nhiều mode khác (kết hợp quyền truy cập, text/binary).
file = open('filename.txt','w')
file.close ()
| Thuộc tính | Ví dụ |
|---|---|
| file.name | Tên tệp (ví dụ names.txt) |
| file.mode | Mode đã mở (ví dụ r) |
| file.closed | False nếu đang mở, True nếu đã đóng |
file = open('names.txt','r')
print(file.name)
print(file.mode)
print(file.closed)
file = open("filename.txt",'w')
string = input('Enter your name:')
file.write(string)
file.close()
>>> print("abc\ndef")
abc
def
>>> print(r"abc\ndef")
abc]ndef
file = open("filename.txt","r")
content = file.read()
print(content)
file.close()
with open("filenames.txt","r") as file:
print(file.read())
name = input("What's your name?")
with open ("names.txt","a") as file:
file.write (f"{name}\n")
import os
os.rename('names.txt','new_names.txt')
import os
os.remove('usernames.txt')
| Hàm | Ý nghĩa | Ghi chú |
|---|---|---|
| os.mkdir | Tạo thư mục mới | ✅ Trong thư mục hiện tại |
| os.rmdir | Xoá thư mục | ⚠️ Cần xoá hết nội dung bên trong trước |
| os.chdir | Đổi thư mục làm việc | Cẩn thận khi dùng path tương đối |
os.mkdir('newdir')
os.rmdir('dirname')
os.chdir('dirname')
import os
path = "D:/code"
contents = os.listdir(path)
print("Directory contents:", contents)
os.getcwd() # => Ex: D:/code
Ghép các thành phần path một cách"thông minh".
import os
base_dir = "D:/data"
filename = "names.txt"
path = os.path.join(base_dir, filename)
print(path) # => "D:/data/names.txt"
Kiểm tra một path có tồn tại không.
import os
base_dir = "D:/data"
filename = "names.txt"
print(os.path.exists(os.path.join(base_dir, filename)))
# (check if there is anything at "D:/data/names.txt" or not)
Ví dụ: students.csv
Hermione,Gryffindor
Harry,Gryffindor
Ron,Gryffindor
Draco,Slytherin
Đọc CSV bằng cách strip và split:
with open("students.csv") as file:
for line in file:
row = line.rstrip ().split(",")
print(f"{row[0]} is in {row[1]}")
{"name": "Nam", "age": 18, "city": "Ha Noi"}
import json
user = json.load("user.json")
print(user) # => {"name": "Nam", "age": 18, "city": "Ha Noi"}
print(user["name"]) # => John
import json
user = {
"name": "Nam",
"age": 18,
"city": "Ha Noi"
}
json.dumps(user, "user.json")
from PIL import Image
path = "img/lec13/sample_image.jpg"
# open the image file
im = Image.open(path)
# show the image file
im.show()