Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การอ่านและเขียนไฟล์ข้อความใน Python

เช่นเดียวกับภาษาอื่นๆ Python มีฟังก์ชัน built-in สำหรับอ่าน เขียน หรือเข้าถึงไฟล์ Python จัดการหลักสองประเภทของไฟล์ ไฟล์ข้อความทั่วไปและไฟล์ไบนารี

สำหรับไฟล์ข้อความ แต่ละบรรทัดจบด้วยอักขระพิเศษ '\n' (รู้จักว่า EOL หรือ End Of Line) สำหรับไฟล์ไบนารี ไม่มีอักขระจบบรรทัด เก็บข้อมูลหลังแปลงเนื้อหาเป็น bit stream

ในส่วนนี้เราจะอภิปรายเกี่ยวกับไฟล์ข้อความ

โหมดการเข้าถึงไฟล์

ลำดับ โหมด & คำอธิบาย
1

r

โหมดอ่านอย่างเดียว เปิดไฟล์ข้อความเพื่ออ่าน หากไฟล์ไม่มี จะ raise I/O Error

2

r+

โหมดอ่านและเขียน หากไฟล์ไม่มี จะ raise I/O Error

3

w

สำหรับเขียนอย่างเดียว หากไฟล์ไม่มี จะสร้างไฟล์ก่อนแล้วค่อยเขียน หากไฟล์มีอยู่ จะลบเนื้อหาและเริ่มเขียนใหม่

4

w+

โหมดเขียนและอ่าน หากไฟล์ไม่มี สร้างไฟล์ได้ หรือหากไฟล์มีอยู่ ข้อมูลจะถูกเขียนทับ

5

a

โหมด append เขียนข้อมูลที่ท้ายไฟล์

6

a+

โหมด append และอ่าน สามารถ append และอ่านข้อมูลได้

ตอนนี้ดูวิธีเขียนไฟล์ด้วยเมธอด writelines() และ write()

ตัวอย่างโค้ด

# สร้างไฟล์ว่างและเขียนบรรทัดต่างๆ
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']
# เปิดไฟล์ในโหมดเขียน
my_file = open('file_read_write.txt', 'w')
my_file.write(line1)
my_file.writelines(lines)  # เขียนหลายบรรทัด
my_file.close()
print('Writing Complete')

ผลลัพธ์

Writing Complete

หลังเขียนบรรทัดแล้ว เราจะ append บรรทัดเพิ่มเติม:

ตัวอย่างโค้ด

# โปรแกรม append บรรทัด
line1 = '\n\nThis is a new line. This line will be appended. \n'
# เปิดไฟล์ในโหมด append
my_file = open('file_read_write.txt', 'a')
my_file.write(line1)
my_file.close()
print('Appending Done')

ผลลัพธ์

Appending Done

สุดท้าย เราจะดูวิธีอ่านเนื้อหาไฟล์จากเมธอด read() และ readline() เราสามารถระบุจำนวนเต็ม 'n' เพื่อได้ตัวอักษรแรก 'n' ตัว

ตัวอย่างโค้ด

# โปรแกรมอ่านจากไฟล์
# เปิดไฟล์ในโหมดอ่าน
my_file = open('file_read_write.txt', 'r')
print('Show the full content:')
print(my_file.read())
# แสดงสองบรรทัดแรก
my_file.seek(0)
print('First two lines:')
print(my_file.readline(), end='')
print(my_file.readline(), end='')
# แสดงถึง 25 ตัวอักษร
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