File operations in Python

Source: Internet
Author: User
This article introduces file operations in Python in detail. For more information, see references. 1. objects must be called, such as values, strings, lists, tuples, dictionaries, and even Files. everything in Python is an object.

 str1 = 'hello' str2 = 'world' str3 = ' '.join([str1,str2]) print(str3)

2. three basic file operation modes: r (only-read), w (only-write), and a (append)

Procedure for file operations:

First, create a file object.

Second, call the file method for operations.

Third, do not forget to close the file. (When the file is not closed, the content will be stored in the cache. although Python will automatically read the content to the disk at the end, it should be used to close the file just in case)

File file1

A faded photo seems to give me a little bit of nostalgia. The hot noodle shop sold by grandpa at the end of the alley is filled with the old backyards. stray cats are sleeping and shaking on the swing. The sunset shines on his eyes. the postcard sent by the DeskMate, lie quietly in the desk.

(1) r mode

In read-only mode, an error is reported when writing content.

F = open ('file1', 'r') f_read = f. read () # read is read by character. read can specify the parameter and set the number of characters to be read. whether an English letter or a Chinese character is a single character. Print (f_read) f. close ()

F = open ('file1', 'r') f_read = f. readline () # readline can only read the first line of code. The principle is to stop reading the first line break. Print (f_read) f. close ()

F = open ('file1', 'r') f_read = f. readlines () # readlines will output the content in the form of a list. Print (f_read) f. close ()

F = open ('file1', 'r') for line in f. readlines () # use the for loop to output the content by string. Print (line) # output a line of content to output a blank line, with a line of content containing a line of space... because each line of content in the file is followed by a line break, and the print () statement itself can wrap. if you do not want to output empty lines, you need to use the following statement: print (line. strip () f. close ()

(2) w mode

Before the operation, all content in the file will be cleared. For example, if 'Hello World' is written to file1, after the program is executed, only 'Hello World' is left in file1'

F = open ('file1', 'W', encoding = 'utf8') # because the default encoding method of Python3 is Unicode, you need to call utf8 when writing files, the file is saved in utf8 mode. in this case, pycharm (the default encoding method is utf8) can be read correctly. when the file is read, the file is in utf8 format, and pycharm is also utf8, so you do not need to call it. F_w = f. write ('Hello World') print (f_w) # interestingly, 'Hello World' is not printed here. only the number of characters written to f. close () are printed ()

(3) a mode

Unlike w mode, a mode does not clear the original content, but moves the cursor to the last position of the content to continue writing new content. For example, append 'Hello World' at the end'

F = open ('file1', 'A') f_a = f. write ('Hello World') print (f_a) # The number of written characters is still printed. f. close ()

Print the file and add the 'helloworld' output after 'Stray cats sleep and shake the Swing '.

In the r mode, we said that the content of the output file is output using the for loop and readlines (). The principle of this output content is to open the file, read all the content into the memory, and then print the input, when the file size is large, this reading method is unreliable, and even causes the machine to crash. We need to close the file in time, as shown below:

F = open ('file', 'r') data = f. readlines () # close the file in time. close () num = 0for I in data: num + = 1 if num = 5: I = ''. join ([I. strip (), 'Hello World']) # Do not splice print (I. strip () f. close ()

For big data files, use the following method:

Num = 0f. close () # Do not close the file too early. Otherwise, the program cannot identify the operation handle. f = open ('file', 'r') for I in f: # for internally converts f into an iterator and uses a row to take a row. Num + = 1 if num = 5: I = ''. join ([I. strip (), 'Hello World']) print (I. strip () f. close ()

3. tell and seek

Tell: query the cursor position in the file

Seek: cursor positioning

F = open ('file', 'r') print (f. tell () # The cursor is at the starting position by default. seek (10) # position the cursor after 10th characters print (f. tell () # output 10f. close () ---------------------- f = open ('file', 'w') print (f. tell () # first clear the content, and the cursor returns to the 0 position f. seek (10) print (f. tell () f. close () ---------------------- f = open ('file', 'A') print (f. tell () # The cursor is at the last position by default. write ('Hello World') print (f. tell () #9 characters behind the cursor, still at the last position f. close ()

4. flush synchronize data from cache to disk

Example to implement the progress bar function

Import sys, time # import sys and time modules for I in range (40): sys. stdout. write ('*') sys. stdout. flush () # flush is equivalent to taking a photo, taking a picture and flushing a time. the code below sleep (0.2) can also implement the same function import time for I in range (40): print ('*', end = '', flush = True) # flush parameter time in print. sleep (0.2)

5. truncate truncation

It cannot be executed in r mode,

In w mode, all data has been cleared and truncate is meaningless,

In a mode, content at the specified position is truncated.

F = open ('file', 'A') f. truncate (6) # Only 6 bytes of content (6 English characters or three Chinese characters) are displayed, and the subsequent content is cleared.

6. Cursor Position Summary

A Chinese character contains two bytes and four methods are involved in the cursor position: read, tell, seek, and truncate.

# -------------------------- Cursor summary head --------------------------------------- f = open ('file', 'r') print (f. read (6) #6 characters print (f. tell () # Location 12 bytes, one Chinese character two bytes f. close () f = open ('file', 'r') f. seek (6) #6 bytes print (f. tell () f. close () f = open ('file', 'A') print (f. tell () # The cursor is at the last position by default. write ('Hello World') print (f. tell () #9 bytes after the cursor, one Chinese character two bytes, still at the last position 182 --> 191f. close () f = open ('file', 'A', encoding = 'utf-8') print (f. truncate (6) # cursor positioning required Location, so it is also a byte. Only 6 bytes of content (6 English letters or three Chinese characters, one Chinese character and two bytes) are displayed, and the subsequent content is cleared. F. close () # ----------------------------- cursor summary end ---------------------------------

7. three other modes: r +, w +, and a +

R +: read/write mode. the cursor is at the starting position by default. when writing data, the cursor automatically moves to the end.

W +: Write-read mode. The original content is cleared and then written.

A +: append read mode. the cursor is at the last position by default and can be read directly.

F = open ('file', 'A') print (f. tell () # end 207 position f. close () f = open ('file', 'R + ') print (f. tell () #0 position print (f. readline () # read the first line f. write ('goat gazelle ') # Move the cursor to the 207 position at the end and write the print (f. tell () #213 (position f. seek (0) # Move the cursor to 0 position print (f. readline () # read the first line f. close ()

8. Modify file content

Idea: due to the relationship between the data storage mechanism, we can only read the content in file 1 and put it in file 2 after modification.

F2 = open ('file2', 'W', encoding = 'utf8') # utf8f1 = open ('file', 'r') must be added when writing data ') num = 0for line in f1: # iterator num + = 1 if num = 5: line = ''. join ([line. strip (), 'yangxiaoling \ n']) # The character string is operated on f2.write (line) f1.close () f2.close ()

9. with statement

You can operate on multiple files at the same time. when the with code block is executed, the file is automatically closed to release memory resources without the need to add f. close (). The following example shows the usage and benefits of.

Rewrite the code in 8 with the with statement


Num = 0 with open ('file', 'r') as f1, open ('file2', 'W', encoding = 'utf8') as f2: for line in f1: num + = 1 if num = 5: line = ''. join ([line. strip (), 'yangxiaorang']) f2.write (line)

10. Summary

The above is all the content of this article, hoping to help you. If you have any questions, leave a message.

For more articles on file operations in Python, refer to PHP Chinese network!

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.