کار با فایلها
خواندن و نوشتن متن با مدیریت صحیح منابع.
خواندن
Python
with open("data.txt", encoding="utf-8") as f:
content = f.read()
with open("data.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())
همیشه از
with استفاده کنید تا فایل خودکار بسته شود.
نوشتن
Python
with open("out.txt", "w", encoding="utf-8") as f:
f.write("خط اول\n")
f.write("خط دوم\n")
# افزودن به انتها
with open("out.txt", "a", encoding="utf-8") as f:
f.write("خط جدید\n")
مسیرها
Python
from pathlib import Path
p = Path("data") / "file.txt"
if p.exists():
text = p.read_text(encoding="utf-8")