کاربرد open
باز کردن فایل.
ساختار فراخوانی
open(file, mode='r', encoding=None)
رفتار و نکات مهم
از with برای بستن فایل استفاده کنید؛ حالت w محتوای قبلی را پاک میکند؛ در مرورگر فایل در محیط مجازی است.
مثال عملی
with open('demo.txt', 'w', encoding='utf-8') as f:
f.write('hello')
with open('demo.txt', encoding='utf-8') as f:
print(f.read())
خروجی مورد انتظار:
hello
تمرین
متن hello را به Python تغییر دهید.
with open('demo.txt', 'w', encoding='utf-8') as f:
f.write('hello')
with open('demo.txt', encoding='utf-8') as f:
print(f.read())
پاسخ پیشنهادی
with open('demo.txt', 'w', encoding='utf-8') as f:
f.write('Python')
with open('demo.txt', encoding='utf-8') as f:
print(f.read())
خروجی پاسخ:
Python