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

Modifier 'U' ทำอะไรเมื่อเปิดไฟล์ด้วย Python?

ใน Python ที่มี Universal Newline Support พารามิเตอร์ Mode ของ open() สามารถเป็น "U" ได้ หมายถึง "Open for input as a text file with universal newline interpretation" สิ่งนี้จำเป็นสำหรับ Cross-Platform Support เนื่องจาก Newlines บน Unix OS แทนด้วย Single Character \n ในขณะที่บน Windows แทนด้วย 2 Characters \r\n เมื่อเปิดใน Python ทุก Line Ending Conventions จะถูกแปลงเป็น "\n" ใน Strings ที่คืนค่าโดย File Methods ต่างๆ เช่น read() และ readline()

ตัวอย่าง

ตัวอย่าง คุณมีไฟล์บน Windows ด้วยข้อความ:

Hello\r\nworld

เมื่อคุณเปิดมันใน Python ด้วย Modifier 'U' และอ่าน:

with open('hello.txt', 'rU') as f:
    print(f.read())

ผลลัพธ์

คุณจะได้ผลลัพธ์:

Hello\nworld