در یک فایل موجود بنویسید(Write to an Existing File)
برای نوشتن روی یک فایل موجود، باید یک پارامتر به آن اضافه کنید
تابع open()
:
"a"
- ضمیمه - به انتهای فایل اضافه می شود
"w"
- نوشتن - هر محتوای موجود را رونویسی می کند
مثال
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f =
open("demofile2.txt", "r")
print(f.read())
مثال
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
توجه: روش "w" کل فایل را بازنویسی میکند.