Python3 file operations (16 ),

Source: Internet
Author: User

Python3 file operations (16 ),
1. File Operations1. Introduction

Computer systems are divided into three parts: computer hardware, operating system, and applications.

Applications written in python or other languages must be stored on the hard disk if they want to permanently Save the data. This involves hardware operations. As we all know, applications cannot directly operate on the hardware, so the operating system is used. The operating system encapsulates complex hardware operations into simple interfaces for users/applications. The files are virtual concepts that the operating system provides to applications to operate on hard disks, users or applications can save their data permanently by operating on files.

With the concept of files, we don't have to worry about the details of operating the hard disk. We just need to pay attention to the file operation process:

#1. open the file, get the file handle, and assign it to a variable #2. Operate the file through the handle #3. close the file
2. in python
1 #1. open the file, get the file handle, and assign a value to the variable 2 f1_open('a.txt ', 'R', encoding = 'utf-8') # The default open mode is r3 4 #2. use a handle to operate the file. 5 data = f. read () 6 7 #3. close file 8 f. close ()
3. fw.open('a.txt ', 'R') Process Analysis
#1. The application initiates a system call open (...) to the operating system (...) #2. open the file in the operating system and return a file handle to the application #3. The application assigns the file handle to the variable f.
4. Emphasize !!!
# Emphasize the first point: Opening a file contains two resources: file opened at the operating system level + Application variables. After a file is operated, the two resources of the file must not be recycled. The recovery methods are as follows: 1. f. close () # reclaim files opened at the operating system level 2. del f # reclaim application-level variables where del f must occur in f. after close (), otherwise, the files opened by the operating system are not closed, and resources are occupied in vain. The python automatic garbage collection mechanism determines that we do not need to consider del f, this requires us to remember f. close () at the beginning, it is easy to forget f. close () method to close. We recommend that you use the with keyword to manage the context with open('a.txt ', 'w') as f: pass with open('a.txt', 'R ') as read_f, open(' B .txt ', 'w') as write_f: data = read_f.read () write_f.write (data)
# Emphasize the second point: f = open (...) the operating system opens the file. If we do not specify the encoding for open, the default encoding for opening the file is clearly determined by the operating system, the operating system uses its own default encoding to open the file, which is gbk in windows and UTF-8 in linux. To ensure that the file is not garbled and stored in any way, you must open the file in any way. F=open('a.txt ', 'R', encoding = 'utf-8 ')
5. file and open in python2
# First, there is only one option to operate the file in python3, that is open () # while in python2, there are two ways: file () and open () can open the file, operations on files have similar usage and parameters. However, there are essential differences between the two methods. file is a file class and file () is used to open files, this is equivalent to constructing a file class,
Open () is used to open a file, which is operated by using python built-in functions. We usually use open () to open the file, and use file as a type, such as type (f) is file
2. File opening Mode
File handle = open ('file path', 'Mode ')

The mode can be a combination of the following methods:

Character Meaning
'R' Open for reading (default)
'W' Open for writing, truncating the file first
'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 (for backwards compatibility; shocould not be used in new code)

 

#1. the file opening mode is available (the default mode is text): r, read-only mode [default mode, the file must exist, and an exception is thrown if the file does not exist] w, write-only mode [unreadable; if it does not exist, it is created. If it exists, the content is cleared.] a, the append write mode [unreadable; if it does not exist, it is created. If it exists, only the content is appended.] #2. for non-text files, we can only use the B mode. "B" indicates that operations are performed in bytes (and all files are stored in bytes, in this mode, you do not need to consider the character encoding of text files, the jgp format of image files, and the avi format of video files.) rb wbab Note: When you open a file in the B mode, the read content is of the byte type. You must provide the byte type when writing data. Encoding cannot be specified #3. "+" indicates that you can read and write a file r + at the same time, read and write [readable, writable] w +, write and read [readable, writable] a +, write and read [readable, writable] x, write-only mode: [unreadable; creation if no data exists. If yes, an error is returned.] x +, write-read [readable, writable] xb
3. File Operations
1 # Master 2 f. read () # read all content, move the cursor to the end of the file 3 f. readline () # Read a row of content, move the cursor to the first line of the second line 4 f. readlines () # read each row and store it in the list. write ('1970 \ n222 \ n') # for writing in text mode, you need to write the line break 7 f. write ('2014 \ n222 \ n '. encode ('utf-8') # for writing in B mode, you need to write the line break 8 f. writelines (['1970 \ n', '1970 \ n']) # file mode 9 f. writelines ([bytes ('192 \ n', encoding = 'utf-8'), '192 \ n '. encode ('utf-8')]) # B mode 10 11 # understand 12 f. readable () # Whether the file is readable 13 f. writable () # Whether the file is readable 14 f. closed # Whether the file is closed 15 f. encoding # If the file opening mode is B, this attribute is not available 16 f. flush () # immediately fl the file content from memory to hard disk 17 f. name
Move the cursor inside the four files

1: read (3 ):

(1) When the file is opened in text mode, it indicates that three characters are read.

(2) When the file is opened in B mode, it indicates that three bytes are read.

2: The cursor moves in other files in bytes, such as seek, tell, and truncate.

Note:

1. There are three ways to move seek: 0, 1, 2, where 1 and 2 must be in B mode, but either mode moves in bytes

2. truncate truncates a file. Therefore, the file must be writable, but cannot be opened by w or w +, because the file is cleared directly, therefore, truncate must test the effect in r +, a, or a + mode.

1 import time 2 with open('test.txt ', 'rb') as f: 3 f. seek (0, 2) 4 while True: 5 line = f. readline () 6 if line: 7 print (line. decode ('utf-8') 8 else: 9 time. sleep (0.2) 10 11 exercise: implement the tail-f function based on seek
5. File Modification

The file data is stored on the hard disk, so there is only one overwrite, there is no such change, we usually see the modified files, are simulated results, specifically, there are two implementation methods:

Method 1: load all the content of the file stored in the hard disk to the memory, which can be modified in the memory. After modification, the memory overwrites the hard disk (word, vim, nodpad ++ editor)

1 with open('a.txt ') as read_f,open('.a.txt. swap ', 'w') as write_f: 2 data = read_f.read () # Read all data into the memory. If the file is large, 3 data = data will be stuck. replace ('Alex ', 'SB') # modify in memory 4 5 write_f.write (data) # write new files 6 7 OS .remove('a.txt ') 8 OS .rename('.a.txt.swap', 'a.txt ')

Method 2: Read the content of the file stored on the hard disk One by one into the memory, write the content to the new file after modification, and overwrite the source file with the new file.

import oswith open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:    for line in read_f:        line=line.replace('alex','SB')        write_f.write(line)os.remove('a.txt')os.rename('.a.txt.swap','a.txt') 
6. Common functions of file objects
Serial number Method and description
1

File. close ()

Close the file. After the file is closed, you cannot read or write the file.

2

File. flush ()

Refresh the internal buffer of the file and directly write data in the internal buffer to the file immediately, instead of passively waiting for writing data in the output buffer.

3

File. fileno ()

Returns an integer file descriptor FD, which can be used for underlying operations such as the read method of the OS module.

4

File. isatty ()

If the file is connected to a terminal device, True is returned; otherwise, False is returned.

5

File. next ()

Returns the next row of the file.

6

File. read ([size])

Reads the specified number of bytes from a file. If it is not specified or is negative, it reads all.

7

File. readline ([size])

Read the entire line, including the "\ n" character.

8

File. readlines ([sizeint])

Read all rows and return the list. If sizeint> 0 is specified, the total number of rows returned is approximately sizeint bytes. The actual read value may be larger than that of sizeint because the buffer zone needs to be filled.

9

File. seek (offset [, whence])

Set the current file location

10

File. tell ()

Returns the current location of the file.

11

File. truncate ([size])

Truncation starts from the beginning of the first line of the file. The truncation is a size character. If there is no size, the file is truncated from the current position. After truncation, all characters After V are deleted, the line feed in the Widnows system represents the size of 2 characters.

12

File. write (str)

Writes a string to a file without returning a value.

13

File. writelines (sequence)

Write a sequence string list to the file. If you need to wrap the string, add the line break of each line on your own.

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.