Python file operations and examples,

Source: Internet
Author: User

Python file operations and examples,

Python file operations and Examples

I. File Operations

1. File Operation Process

  • Open the file, get the file handle, and assign it to a variable.
  • Operate a file using a handle
  • Close file

The existing files are as follows:

Last night, the cold was not audible. It's already three more. To bypass the order. People quietly, outside the curtain month Xiaoming. The name of the white-headed hacker is a success. I want to pay for my worries. Few Zhiyin, who listens to the broken string. F = open ('John Mountain ') # open the file data = f. read () # obtain the file content f. close () # close the file

NOTE: if in the win, the hello file is saved by utf8. When opening a file, the open function is a file opened by the operating system, while the win operating system uses gbk encoding by default, so it will be garbled to open it directly. f = open ('hello', encoding = 'utf8') is required. If the hello file is saved by gbk, open it directly.

2. File opening Mode

Character Meaning

'r'    open for reading (default)'w'    open for writing, truncating the file first'x'    create a new file and open it for writing'a'    open for writing, appending to the end of the file if it exists'b'    binary mode't'    text mode (default)'+'    open a disk file for updating (reading and writing)'U'    universal newline mode (deprecated)

First, we will introduce three basic modes:

# F = open ('chongshan 2', 'w') # open the file # f = open ('chongshan 2', 'A') # open the file # f. write ('Wait for free 1 \ n') # f. write ('White juvenile header 2 \ n') # f. write ('empty sorrow! 3 ')

3. File Operations

F = open ('chongshan ') # open the file # data1 = f. read () # Get file content # data2 = f. read () # Get file content # print (data1) # print ('... ', data2) # data = f. read (5) # Get file content # data = f. readline () # data = f. readline () # print (f. _ iter __(). _ next _ () # for I in range (5): # print (f. readline () # data = f. readlines () # for line in f. readlines (): # print (line) # question: print all rows. Add 'end 3' # for index, line in enumerate (f. readlines (): # if index = 2: # line = ''. join ([line. strip (), 'end 3']) # print (line. strip () # Remember: we will use the following # count = 0 # for line in f: # if count = 3: # line = ''in the future ''. join ([line. strip (), 'end 3']) # print (line. strip () # count + = 1 # print (f. tell () # print (f. readline () # print (f. tell () # tell occupies one English character and three Chinese characters, which are different from read. # print (f. read (5) # A Chinese Character occupies three characters # print (f. tell () # f. seek (0) # print (f. read (6) # After read, whether it is a Chinese character or an English character, it is regarded as a unified unit, read (6), now read 6 Chinese characters # operation on terminal: f = open ('chongshan 2', 'w') # f. write ('Hello \ n') # f. flush () # f. write ('World') # application: progress bar # import time, sys # for I in range (30): # sys. stdout. write ("*") # sys. stdout. flush () # time. sleep (0.1) # f = open ('chongshan 2', 'w') # f. truncate () # truncate all # f. truncate (5) # truncate all # print (f. isatty () # print (f. seekable () # print (f. readable () f. close () # close a file

Next we will continue to expand the file mode:

# F = open ('chongshan 2', 'w') # open the file # f = open ('chongshan 2', 'A') # open the file # f. write ('Wait for free 1 \ n') # f. write ('White juvenile header 2 \ n') # f. write ('empty sorrow! 3') # f. close () # r +, w + mode # f = open ('chongshan 2', 'r + ') # open a file in read/write mode # print (f. read (5) # read # f. write ('hello') # print ('------ ') # print (f. read () # f = open ('chongshan 2', 'W + ') # open the file in write-read mode # print (f. read (5) # Nothing, because the text is first formatted # f. write ('Hello alex ') # print (f. read () # still cannot read # f. seek (0) # print (f. read () # The difference between w + AND a + is whether to overwrite the entire file # OK. The point is that I want to add a line after the third line of the text: 'Hello Yue Fei! '# Some people said, have you made any changes before? Eldest Brother, print the modified content, and modify the file now !!! # F = open ('chongshan 2', 'r + ') # open the file in write-Read mode # f. readline () # f. readline () # f. readline () # print (f. tell () # f. write ('Hello Yue fei') # f. close () # It's different from what you want! What should I do when file modification is involved? # F_read = open ('chongshan ', 'R') # open a file in write-Read mode # f_write = open ('chongshan _ back', 'w ') # open a file in write-Read mode # count = 0 # for line in f_read: # if count = 3: # f_write.write ('hello, Yue Fei \ n') # else: # f_write.write (line) # another way: # if count = 3: # line = 'hello, Yue Fei 2 \ n' # f_write.write (line) # count + = 1 # binary mode # f = open ('chongshan 2', 'wb ') # reading a file in binary format # f = open ('chongshan 2', 'wb') # Writing a file in binary format # f. write ('Hello alvin! '. Encode () # B' hello alvin! 'Is a binary data, only for viewing, not displayed as 010101

Note 1: Both py2 and py3 can be replaced by equal bytes in the r + mode, but it does not make any sense!

NOTE 2: Some users will use readlines to obtain the content list, modify the content through the index, and then rewrite the list to write the file.

There is a big problem with this idea. If the data is large, your memory will not be able to handle it, and our approach can be optimized through the iterator.

Supplement: rb mode and seek

In py2:

# The night was cold. f = open ('test', 'R',) # open the file in write-Read mode. read (3) # f. seek (3) # print f. read (3) # Night # f. seek (3, 1) # print f. read (3) # cold # f. seek (-4, 2) # print f. read (3) # Ming

In py3:

# Test. f = open ('test', 'rb',) # open the file in write-Read mode. read (3) # f. seek (3) # print (f. read (3) # B '\ xe5 \ xa4 \ x9c' # f. seek (3, 1) # print (f. read (3) # B '\ xe5 \ xaf \ x92' # f. seek (-4, 2) # print (f. read (3) # B '\ xe9 \ xb8 \ xa3' # conclusion: In py3, If you want character data, that is, for viewing, the r mode is used, in this way, f. the read data is a decode # unicode data. However, if this data is not read, it is only used for transmission, such as file upload, so I don't need decode # Just transfer bytes directly, so we need to use the rb mode at this time. # In py3, there is a strict line that distinguishes bytes and unicode. For example, the use of seek is a byte seek in py2 and py3, # But in py3, you must declare that the f type is rb, and fuzzy search is not allowed. # suggestion: directly use the rb mode when you read and write files later. decode the code to decode the code.

4. with statement

To avoid forgetting to close a file after it is opened, you can manage the context, that is:

with open('log','r') as f:    pass

In this way, when the with code block is executed, the file resources are automatically closed and released internally.

After Python 2.7, with supports managing the context of multiple files at the same time, namely:

with open('log1') as obj1, open('log2') as obj2:  pass2

If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article. Thank you for your support!

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.