Python file input and output

Source: Internet
Author: User

The python file object can access not only normal disk files, but also file objects (such as URL addresses) at the abstraction level

Opening file open () files () function can be arbitrarily substituted

fp = open ('/etc/test.txt','R')#Open as read-onlyfp = open ('Test.txt','W')#Open in write modefp = open ('Data.txt','r+')#Open in Read and write modeFP = open (r'C:\io.sys','RB')#Open in binary read-only mode

Input:

Tp.read (size)        # reads a size byte from a file tp.readline ()        # reads one line at a time tp.readlines ()        # Read all rows of the file

Output:

Fp.write ('test test')

Moving within files

Seek ( -12,1)        # move forward 12 characters in the current position #-12 minus means move forward  1 means the current position 0 means the file starts 2 means end of file # use tell () to return the position in the current file before use
#例子
f = open ('Test.txt','w+')PrintF.tell () f.write ('Text line 1\n')PrintF.tell () f.write ('Test Line 2\n')PrintF.tell () F.seek (-13,1)PrintF.tell () f.write ('Test Line 3\n')PrintF.tell () F.seek (-13,1)PrintF.tell ()

After you have finished working on the file, be sure to close the file Fp.close ()

    

Python file input and output

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.