Python file operation differences in read, write, append

Source: Internet
Author: User

The common patterns for opening files are:

    • R, read-only mode "default"
    • W, write-only mode "unreadable; not exist" created; empty content;
    • A, append mode "readable; not present, create; append content only;"

"+" means you can read and write a file at the same time

    • r+, read and write "readable, can write" "can be understood as read before writing, do not erase the original file content, the pointer in 0"
    • w+, write read "Readable, can write" "can be understood as read first, erase the original file content, the pointer in 0"
    • A +, write read "Readable, can write" "does not erase the original file content, but the pointer directly to the last, read the original content first reset the pointer"
Mode can do operation If the file does not exist whether to overwrite pointer position
R Read Only Error - 0
r+ Readable and writable Error Whether 0
W can only write Create Is 0
w+ can be written and readable Create Is 0
A can only write Create No, append write At last
A + Readable and writable Create No, append write At last

You can make a test file, modify the next open mode, and then output look at the pointer difference

f=open(‘I:\\python\\test\\text.txt‘,‘r+‘)print(‘指针在:‘,f.tell())lines=f.read()if f.writable():    f.write(‘nono\n‘)else:    print("此模式不可写")print(‘指针在:‘,f.tell())f.close()

A + mode, although can read, but the pointer is to the end, direct read, will not be content, you can use Seek () to reset the pointer

f=open(‘I:\\python\\test\\text.txt‘,‘a+‘)print(‘指针在:‘,f.tell())lines=f.read()print(‘文件内容是:‘,lines)  #输出为空print(‘seek 0‘)f.seek(0)print(‘指针在:‘,f.tell())lines=f.read()print(‘文件内容是:‘,lines)if f.writable():    f.write(‘nono\n‘)else:    print("此模式不可写")print(‘指针在:‘,f.tell())f.close()

Python file operation differences in read, write, append

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.