Summary of python file operations,

Source: Internet
Author: User

Summary of python file operations,

File Read operations

Example:

Print ("-> file handle acquisition, read operation:") f = open ('untitle', 'R', encoding = 'utf8') d = f. read () f. close () print (d) print ('-> Example 2:') f = open ('untitle', 'R', encoding = 'utf8') e = f. read (9) f. close () print (e) # In python3, both Chinese and English occupy 1 space.

Running result:

Copy code

-> File handle acquisition and read operations: Last night, stars were painted on the east side of the west side of the building last night, without the colorful Phoenix. the wings were shining with each other.-> Example 2: Last night, stars were painted on the wind.

File write operations

Knowledge point:

1. Format and clear the file before writing

2. Clear the open w method.

Print ("write operation, when writing a file, you cannot call the read method. When reading a file, you cannot call the write method") f = open ('python', 'w ', encoding = 'utf8') f. write ("I must learn python \ nbecause, python is important \ n") f. write ("java is better? ") F. write (" maybe ") # The preceding statement does not contain line breaks, so the output content is followed by f. close ()

Running result:

After opening the file, the following information is displayed:

I must learn python because, python is important java is better?maybe

File append Method

Syntax format:

F = open ('filename ', 'A', 'encoding= utf8 ')

This method is used in the append mode: 1. In a blank file, the content is directly written from the beginning; 2. If the file has content, the content will continue to be written at the end.

Example:

F = open ('python', 'A', encoding = 'utf8') f. write ("flowers bloom and bloom") f. close ()

Running result:

I must learn python because, python is important java is better? Maybe flowers bloom and bloom

Readline and readlines

Readline reads data row by row.

Readlines is full-text read

Example:

Print ("readline method") f = open ('untitle', 'R', encoding = 'utf8') a = f. readline () print ("the cursor position at this time:", f. tell () B = f. readline () print ("the cursor position at this time:", f. tell () print (. strip () # strip is the print (B. strip () print ("readlines method, the content of each row is composed of a list to print") f = open ('untitle', 'R', encoding = 'utf8 ') c = f. readlines () print (c) print (id (f) for I in c: print (I. strip () print ("Traversal method") f. seek (0) for I in f: print (I. strip () f. close () # In file operations, the close () method must not be forgotten.

Running result:

Readline method: cursor position at this time: 23 cursor position at this time: 46 last night, stars, last night, the wind painted building, the West Side of the guitang East readlines method, the contents of each row are displayed in a list. ['Last night's stars last night wind \ n', 'guitang East \ n' on the west side of the painted building, 'no colorful Phoenix Wings \ n ', 'Hearts and souls] 378268245344280 last night, stars, last night, the wind painted building, the West Side, the east side, the east side, no colorful Phoenix, the wings, the hearts of the soul, the way through the Traversal method last night, the wind painted building, the West Side, the Guangxi Hall, the East Side

Tell () and seek () Methods of Files

Example:

F = open ('untitle', 'R', encoding = 'utf8') f. read (4) print ('current cursor position', f. tell () f. seek (10) print ('current cursor position', f. tell () f. close () # When reading, a Chinese character is counted as three characters

Running result:

Current cursor position 12
Current cursor position 10

Flush Method for file operations

import sys,timefor i in range(20): sys.stdout.write("#") sys.stdout.flush() time.sleep(1)

Truncate Method

F = open ('test', 'w') f. write ("hello") f. write ("\ n") f. write ("python") f. flush () # in this way, data in the memory will be written to diskf without executing the close method. close () f = open ('test', 'A') f. truncate (2) # truncation method. The cursor starts from 2 and then truncate f. close ()

Other File Methods: r + read/write Methods

Read & write based on Characters

Of course, the most basic file operation is to read and write data in the file. This is easy to grasp. Open a file to perform the write operation:

fileHandle = open ( 'test.txt', 'w' )

'W' indicates that the file will be written into data, and the rest of the statement is easy to understand. The next step is to write data to a file:

fileHandle.write ( 'This is a test.\nReally, it is.' )

This statement writes "This is a test." to the first line of the file, "Really, it is." to the second line of the file. Finally, we need to clear the file and close the file:

fileHandle.close()

As you can see, in Python's object-oriented mechanism, this is indeed very simple. It should be noted that when you use the "w" method to write data in the file again, all the original content will be deleted. If you want to retain the original content, you can use the "a" method to append data to the end of the file:

fileHandle = open ( 'test.txt', 'a' ) fileHandle.write ( '\n\nBottom line.' ) fileHandle.close()

Then we read test.txt and show the content:

fileHandle = open ( 'test.txt' ) print fileHandle.read() fileHandle.close()

The preceding statement reads the entire file and displays its data.

Row-based read/write line

fileHandle = open ( 'test.txt' ) print fileHandle.readline() # "This is a test." fileHandle.close() 

You can also save the file content to a list:

fileHandle = open ( 'test.txt' ) fileList = fileHandle.readlines() for fileLine in fileList: print '>>', fileLine fileHandle.close() 

Or read several bytes of content in the file at a time:

FileHandle = open ('test.txt ') print fileHandle. read (1) # "T" fileHandle. seek (4) print FileHandle. read (1) # "(the original article is wrong)

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.