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

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

Related Article

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.