Python path-file operations,

Source: Internet
Author: User

Python path-file operations,
File Operations

1. objects must be called, such as values, strings, lists, tuples, dictionaries, and even files. Everything in Python is an object.

1 str1 = 'hello'2 str2 = 'world'3 str3 = ' '.join([str1,str2])4 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

1. A faded photo. 2. It seems to give me a little bit of nostalgia. 3. Hot noodle soup sold by grandpa at the end of the alley. 4 The taste is filled with the old backyards. 5. stray cats are sleeping and shaking the swing. 6. The sunset shines on his eyes; 7. the postcard sent by the table lie quietly in the desk.

(1) r mode

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

1 f = open ('file1', 'R') 2 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. 3 print (f_read) 4 f. close ()
1 f = open ('file1', 'R') 2 f_read = f. readline () # readline can only read the first line of code. The principle is to stop reading the first line break. 3 print (f_read) 4 f. close ()
1 f = open ('file1', 'R') 2 f_read = f. readlines () # readlines will output the content in the form of a list. 3 print (f_read) 4 f. close ()
1 f = open ('file1', 'R') 2 for line in f. readlines () # Use the for loop to output the content by string. 3 print (line) # output a line of content to output an empty 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 () 4 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'

1 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. 2 f_w = f. write ('Hello World') 3 print (f_w) # interestingly, 'Hello world' is not printed here, and only the number of characters 4 f are written. close ()

(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'

1 f = open ('file1', 'A') 2 f_a = f. write ('Hello World') 3 print (f_a) # It Still prints the number of characters written 4 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:

1 f = open ('file', 'R') 2 data = f. readlines () # close the file in time. 3 f. close () 4 5 num = 0 6 for I in data: 7 num + = 1 8 if num = 5: 9 I = ''. join ([I. strip (), 'Hello world']) # Do not splice 10 print (I. strip () 11 f. close ()

For big data files, use the following method:

1 num = 02 f. close () # Do not close the file too early. Otherwise, the program cannot recognize the operation handle f.3 f = open ('file', 'R') 4 for I in f: # for internally converts f into an iterator and uses a row to take a row. 5 num + = 16 if num = 5:7 I = ''. join ([I. strip (), 'Hello world']) 8 print (I. strip () 9 f. close ()

3. tell and seek

Tell: query the cursor position in the file

Seek: cursor Positioning

1 f = open ('file', 'R') 2 print (f. tell () # The cursor is at the starting position by default. 3 f. seek (10) # position the cursor after 10th characters 4 print (f. tell () # output 10 5 f. close () 6 -------------------- 7 f = open ('file', 'w') 8 print (f. tell () # first clear the content, and the cursor returns to the 0 position 9 f. seek (10) 10 print (f. tell () 11 f. close () 12 -------------------- 13 f = open ('file', 'A') 14 print (f. tell () # The cursor is at the last position by default. write ('Hello World') 16 print (f. tell () #9 characters behind the cursor, still at the last position 17 f. close ()

4. flush synchronize data from cache to disk

Example to implement the progress bar Function

1 import sys, time # import sys and time Modules 2 for I in range (40): 3 sys. stdout. write ('*') 4 sys. stdout. flush () # flush is equivalent to taking a photo. Take a picture and rinse it for 5 time. sleep (0.2) 6 the code below can also implement the same function 7 import time 8 for I in range (40): 9 print ('*', end = '', flush = True) # flush parameter 10 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.

1 f = open ('file', 'A') 2 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.

1 # -------------------------- cursor summary head --------------------------------------- 2 f = open ('file', 'R') 3 print (f. read (6) #6 Characters 4 print (f. tell () # Location 12 bytes, one Chinese character two bytes 5 f. close () 6 7 f = open ('file', 'R') 8 f. seek (6) #6 bytes 9 print (f. tell () 10 f. close () 11 12 f = open ('file', 'A') 13 print (f. tell () # The cursor is at the last position by default. 14 f. write ('Hello World') 15 print (f. tell () #9 bytes behind the cursor, two bytes for one Chinese character, still at the last position 182 --> 19116 f. close () 17 18 f = open ('file' , 'A', encoding = 'utf-8') 19 print (f. truncate (6) # It is also a byte because the cursor must be positioned. 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. 20 f. close () 21 # ----------------------------- 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.

1 f = open ('file', 'A') 2 print (f. tell () #207 position at the End 3 f. close () 4 5 f = open ('file', 'r + ') 6 print (f. tell () #0 position 7 print (f. readline () # Read the first row 8 f. write ('goat gazelle ') # move the cursor to the 207 position at the end and write 9 print (f. tell () #213 position 10 f. seek (0) # move the cursor to 0 position 11 print (f. readline () # Read the first row 12 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.

1 f2 = open ('file2', 'w', encoding = 'utf8') # utf8 2 f1 = open ('file', 'R') must be added when writing data ') 3 num = 0 4 for line in f1: # iterator 5 num + = 1 6 if num = 5: 7 line = ''. join ([line. strip (), 'yangxiaoling \ n']) # The string is operated on 8 f2.write (line) 9 f1.close () 10 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

1 num = 02 with open ('file', 'R') as f1, open ('file2', 'w', encoding = 'utf8') as f2: 3 for line in f1: 4 num + = 15 if num = 5:6 line = ''. join ([line. strip (), 'yangxiaorang']) 7 f2.write (line)

 

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.