File I/O is one of the most important techniques in Python, and it is very simple to do I/O to files in Python.
1. Open File
Grammar:
Open (name[, mode[, Buffering])
1.1 File Mode
' R ' Read mode 'w' write mode 'a' Append mode ' b ' binary mode (can be added to other modes using)'+' read/write mode (can add other modes to use)
1.2 Buffers
The third parameter of the Open function ( buffering
), which represents the buffer of the file, when the buffer is greater than 0 o'clock (equal to 0 o'clock unbuffered, all read and write operations are directed against the hard disk), Python stores the contents of the file in the buffer (in memory), so that the program runs faster, and only use flush
the Or close
, the data in the buffer is updated to the hard disk.
2. file reading and writing
2.1 Writing Files
#!/usr/bin/python#-*-coding:utf-8-*-#Open Filef = Open (r'D:\python\File\Pra_1.txt','W')Try : #Write FileF.write ('My name is OLIVER')finally: #Close FileF.close ()
2.2 Reading files
# !/usr/bin/python # -*-coding:utf-8-*-f = open (R'D:\python\File\Pra_1.txt','R ' )print(F.read ()) F.close ()
3. File Special Read
3.1 Traversal of each character, one read
Method One:
# !/usr/bin/python # -*-coding:utf-8-*-f = open (R'D:\python\File\Pra_1.txt','R ' = f.read (1) while char: print(char) = F.read (1) f.close ()
Method Two:
# !/usr/bin/python # -*-coding:utf-8-*-f = open (R'D:\python\File\Pra_1.txt','R ' while True: = f.read (1) if the line: Break Print (line) f.close ()
3.2 Traversing each row read
Pra_2.txt File Contents:
# !/usr/bin/python # -*-coding:utf-8-*-f = open (R'D:\python\File\Pra_2.txt','R ' ) while True: = f.readline () if not Line:break print(line) f.close ()
Read Result:
Python file I/O