Python file I/O

Source: Internet
Author: User

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


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.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 '  = (1) while char:    print(char)    = (1) f.close ()

Method Two:

# !/usr/bin/python # -*-coding:utf-8-*-f = open (R'D:\python\File\Pra_1.txt','R '  while True:    = (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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.