Python file Write and save

Source: Internet
Author: User

Python uses the open () function to open the file return object:

Open second parameter

"R" Open a file as read-only
"W" Open file in Write method, overwrite stored content
"X" Open throws an exception if the file is present
A Opens the file in write mode and, if it exists, adds the file at the end
"B" Open a file in binary mode
"T" Open a file in text mode (default)
"+" Read/write mode (can be added to other modes)
U Universal Line break support

Methods for file objects :

Close () Close File
Read (Size=-1) Reads a size character from a file, reads all remaining characters when not given a size or a given negative value, and then returns the string back as a character
ReadLine ()

Reads a whole line of string from a file

Write (str) Writes the string str to the file
Writelines (seq) To write a string sequence to a file seq,seq should be an iterative object that returns a string
Seek (Offset,from)

Move the file pointer in the file, from the from (0 for the file start position, 1, for the current position, 2 for the end of the file) offset by offsets bytes

Tell () Returns the current position in the file

Read and locate the file:

1>>>f=open ("d:/text File/1.txt")2>>>F.read ()3 'Hello, friends \nhello friend'4>>>F.tell ()5246>>>f.seek (0,0)#set the file pointer to the starting position7 08>>>f.read (5)#read 5 bytes per byte9 'Hello, friend.'   Ten  One>>> F.readline ()#reads a line (that is, from the text pointer to \ n) A 'Hello, friend \ n'    
13
14
>>>f.seek (0,0)
>>>for Each_line in F:
Print (Each_line) #使用迭代来返回每一行文本

Write to File:


If you write to a file, make sure that you open it in "w" or "a" mode, and then tune the writer () function

1 f=open ("d:/text file/1.txt", "w")23 f.write ("  Hello everyone ")45 f.close ()

Actual combat:

Python file Write and save

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.