Python file Operations

Source: Internet
Author: User

Now there are the following files:

1 su Shi's "Jiangcheng son, ten years of life and death"2 ten years of life and death two boundless,3 not thinking,4 self-remembering. 5 Thousands of miles of solitary graves,6 nowhere to say bleak. 7 Even if we meet each other without knowledge,8 Dust,9 The temples are like frost. Ten The night came to the return of the dream.  One Small Xuan window, A just dressing.  - were just no words, - only tears thousand lines.  the material to be heartbroken annually: - Moon Night, -Short Matsuoka.
1 f = open (' jiangcheng Sub. txt'# opens file 2 data=f.read ()# Get file Contents 3 # Close File

To prevent problems with file formats, you should write

f = Open (' Jiangcheng sub. txt ', ' r ', encoding= ' UTF8 ')

File operations

File operation mode

' a ' Add mode ' W ' Write mode ' R ' Read Mode ' r+ ' read from 0 position, start writing at last position ' w+ ' empty First, then read and write ' A + ' cursor defaults to last position
1F.read ()#reads the entire contents of the file, the output string2F.read (2)#take the first two units, Chinese and English characters are counted as one unit3F.readline ()#read a line of content4F.readlines ()#read multiple lines of content, output is a list5F.tell ()#output cursor location, by character, one Chinese three characters6F.seek ()#Move Cursor Position7  forIinchF:#Make an iterator out of the for-speaking object. Take a row with one line8F.flush ()#Writes the data in the cache to the disk, and the normal operation Close () is written9F.truncate ()#truncation, ' r ' mode cannot execute, specifies truncation of content after specified position

Open the file with the with operation, and automatically close when the operation is completed

With open ('log'R') as F:

Python file Operations

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.