เรียนเขียนโปรแกรมง่ายๆกับ Expert Programming Tutor ในบท Python File Write/Create file
การเขียนไปยังไฟล์ที่มีอยู่
ในการเขียนไปยังไฟล์ที่มีอยู่ นักเรียนจะต้องเพิ่มพารามิเตอร์ในฟังก์ชั่น open ()
"a" - append - จะต่อท้ายไฟล์
"w" -write - จะเขียนทับเนื้อหาใดๆ ที่มีอยู่
ตัวอย่าง
เปิดไฟล์ "demofile2.txt" และเพิ่มเนื้อหาต่อท้ายไฟล์
| 
			 f = open("demofile2.txt", "a") #open and read the file after the appending:  | 
		
ผลลัพธ์
| 
			 f = open("demofile2.txt", "a") #open and read the file after the appending:  | 
		
 หมายเหตุ: วิธีการ "w" จะเขียนทับไฟล์ทั้งหมด
สร้างไฟล์ใหม่
ในการสร้างไฟล์ใหม่ใน Python ให้ใช้เมธอด open () พร้อมหนึ่งในพารามิเตอร์ต่อไปนี้
"x" - create - จะสร้างไฟล์ส่งคืนข้อผิดพลาดหากไฟล์นั้นมีอยู่
"a" - append - จะสร้างไฟล์หากไฟล์ที่ระบุไม่มีอยู่
"w" - write - จะสร้างไฟล์หากไฟล์ที่ระบุไม่มีอยู่
ตัวอย่าง
สร้างไฟล์ชื่อ "myfile.txt"
| 
			 f = open("demofile2.txt", "a") #open and read the file after the appending:  | 
		
ตัวอย่าง
| 
			 f = open("myfile.txt", "x")  | 
		
ผลลัพธ์: สร้างไฟล์ว่างใหม่!
ตัวอย่าง
สร้างไฟล์ใหม่หากไม่มีอยู่
| 
			 f = open("myfile.txt", "x")  | 
		
ในบทความนี้จะพูดถึงเรื่องการเขียนไปยังไฟล์ที่มีอยู่ นักเรียนจะต้องเพิ่มพารามิเตอร์ในฟังก์ชั่น open() พร้อมหนึ่งพารามิเตอร์
แปลจากhttps://www.w3schools.com/python/python_file_write.asp
Tag ที่น่าสนใจ: python file_writing file_creation open_function append_mode write_mode create_mode text_file file_manipulation programming_tutorial code_example
หากมีข้อผิดพลาด/ต้องการพูดคุยเพิ่มเติมเกี่ยวกับบทความนี้ กรุณาแจ้งที่ http://m.me/Expert.Programming.Tutor
085-350-7540 (DTAC) 
    084-88-00-255 (AIS) 
    026-111-618 
    หรือทาง EMAIL:  NTPRINTF@GMAIL.COM
            Copyright (c) 2013 expert-programming-tutor.com. All rights reserved. | 085-350-7540 | 084-88-00-255 | ntprintf@gmail.com
