เช่นเดียวกับภาษาอื่นๆ Python มีฟังก์ชันในตัวสำหรับการอ่าน เขียน หรือเข้าถึงไฟล์ Python สามารถจัดการไฟล์ได้สองประเภทเป็นส่วนใหญ่ ไฟล์ข้อความปกติและไฟล์ไบนารี
สำหรับไฟล์ข้อความ แต่ละบรรทัดจะสิ้นสุดด้วยอักขระพิเศษ '\n' (เรียกว่า EOL หรือ End Of Line) สำหรับไฟล์ไบนารีไม่มีอักขระลงท้ายบรรทัด มันบันทึกข้อมูลหลังจากแปลงเนื้อหาเป็นบิตสตรีม
ในส่วนนี้เราจะพูดถึงเกี่ยวกับไฟล์ข้อความ
โหมดการเข้าถึงไฟล์
| Sr.No | โหมด &คำอธิบาย |
|---|---|
| 1 | ร เป็นโหมดอ่านอย่างเดียว มันเปิดไฟล์ข้อความสำหรับการอ่าน เมื่อไฟล์ไม่มีอยู่ จะทำให้เกิดข้อผิดพลาด I/O |
| 2 | r+ โหมดนี้สำหรับการอ่านและการเขียน เมื่อไฟล์ไม่มีอยู่ จะทำให้เกิดข้อผิดพลาด I/O |
| 3 | w สำหรับงานเขียนเท่านั้น เมื่อไฟล์ไม่มีอยู่ ไฟล์จะสร้างไฟล์ขึ้นมาก่อน จากนั้นจึงเริ่มเขียน เมื่อไฟล์มีอยู่ ไฟล์นั้นจะลบเนื้อหาของไฟล์นั้นออก และเริ่มเขียนตั้งแต่ต้น |
| 4 | w+ เป็นโหมดเขียนและอ่าน เมื่อไฟล์ไม่มีอยู่ สามารถสร้างไฟล์ได้ หรือเมื่อมีไฟล์อยู่ ข้อมูลจะถูกเขียนทับ |
| 5 | ก นี่คือโหมดผนวก ดังนั้นมันจึงเขียนข้อมูลที่ท้ายไฟล์ |
| 6 | a+ โหมดผนวกและอ่าน สามารถผนวกข้อมูลและอ่านข้อมูลได้ |
มาดูวิธีการเขียนไฟล์โดยใช้เมธอด writelines() และ write()
โค้ดตัวอย่าง
#Create an empty file and write some lines
line1 = 'This is first line. \n'
lines = ['This is another line to store into file.\n',
'The Third Line for the file.\n',
'Another line... !@#$%^&*()_+.\n',
'End Line']
#open the file as write mode
my_file = open('file_read_write.txt', 'w')
my_file.write(line1)
my_file.writelines(lines) #Write multiple lines
my_file.close()
print('Writing Complete')
ผลลัพธ์
Writing Complete
หลังจากเขียนบรรทัดแล้ว เราก็ต่อท้ายบางบรรทัดในไฟล์
โค้ดตัวอย่าง
#program to append some lines
line1 = '\n\nThis is a new line. This line will be appended. \n'
#open the file as append mode
my_file = open('file_read_write.txt', 'a')
my_file.write(line1)
my_file.close()
print('Appending Done')
ผลลัพธ์
Appending Done
ในที่สุด เราจะมาดูวิธีการอ่านเนื้อหาไฟล์จากเมธอด read() และ readline() เราสามารถระบุเลขจำนวนเต็ม 'n' เพื่อรับอักขระ 'n' ตัวแรกได้
โค้ดตัวอย่าง
#program to read from file
#open the file as read mode
my_file = open('file_read_write.txt', 'r')
print('Show the full content:')
print(my_file.read())
#Show first two lines
my_file.seek(0)
print('First two lines:')
print(my_file.readline(), end = '')
print(my_file.readline(), end = '')
#Show upto 25 characters
my_file.seek(0)
print('\n\nFirst 25 characters:')
print(my_file.read(25), end = '')
my_file.close()
ผลลัพธ์
Show the full content: This is first line. This is another line to store into file. The Third Line for the file. Another line... !@#$%^&*()_+. End Line This is a new line. This line will be appended. First two lines: This is first line. This is another line to store into file. First 25 characters: This is first line. This