Python file operations,

Source: Internet
Author: User

Python file operations,

The file object is created using the open function. The operations on the file are divided into three steps:

1. open the file and obtain the file handle.

2. read/write file content through file handle

3. close the file.

Note:

There are three file opening modes:

1. w write mode, which cannot be read and can only be written. If the file does not exist, create

2. r read mode. data cannot be written, but can only be read. Files must exist. If file open mode is not passed, the r read mode is used by default.

3. a append mode, which can only be written. add content at the end of the file

Open the file in w mode and write the following content:

Fp = open('file.txt ', 'w') fp. write ('hhh') # If you open an existing file in w mode, the previous file content will be cleared and hhh will be written again.

Open the file in r mode and read the file content as follows:

Fp = open('file.txt ', 'R', encoding = 'utf-8') # The default character set for windows is gbk, which must be set to UTF-8, the encoding parameter can specify the file encoding print (fp. read () # read the object content. The returned result type is a string.

Open a non-existing file in r mode, as shown below:

Fp = open('a.txt ', 'R') # If the opened file does not exist, the following error occurs: FileNotFoundError: [Errno 2] No such file or directory: 'a.txt' print (fp. read ())

Open a non-existing file in the mode and write the content as follows:

Fp = open('a.txt ', 'A') # write a non-existent file name in append mode. If the file does not exist, create fp. write ('y') # add content at the end of the file
Common file operations are as follows:

Read (), readline (), readlines () read File Content operations:

Fp = open('file.txt ', 'a +') # a + mode. The pointer is at the end of the file. You must move the pointer to the initial file to read the content fp. seek (0) # when reading the file content multiple times, you must move the cursor to the initial position. Otherwise, the read content is empty print (fp. read () # read the file content, return a string, move the pointer to the last position, and do not use it when there is a large file, because the file content will be read to the memory, if the memory is not enough, memory will pop up
Fp. seek (0) # Move the pointer to the initial position
Print (fp. readlines () # Read the file content. A list is returned, and the element is the data of each row. this parameter is not used for large files because the file content is read to the memory. If the memory is insufficient, memory will pop up
Fp. seek (0)
Print (fp. readline () # Read Only one row of the file content and return a string

Efficient operations for reading large files:

If you use the preceding read () and readlines () Methods to operate a file, all the content of the file will be read into the memory. In this way, there will be more memory data, which is very slow and efficient, it is to read a row of operations, read content is released from the memory:

F = open('file.txt ') for line in f: print (line). line is the content of each file line. After reading a row, the memory of one row is released.

Write () and writelines () operations to write File Content:

Fp = open('file.txt ', 'a +') fp. write ('000000' + '\ n') # When writing a file, only the string fp can be written. writelines (['1970 \ n', '1970 \ n', '1970 ']) # writelines can write the list to the file fp. seek (0) print (fp. readlines () # execution result: ['192 \ n', '192 \ n', '192 \ n', '192 \ n']

Flush () refreshes the file content buffer as follows:

Import timefp = open('file.txt ', 'w') # open the file fp in w mode. write ('Ode to Joy ') # write the file content fp. flush () # refresh the internal buffer of the file and directly write data in the internal buffer to the file, instead of passively waiting for the output buffer to write time. sleep (30) # The sleep time is 30sfp. close () # close a file

Tell () to view the cursor position:

Fp = open('file.txt ', 'r +') print (fp. read () # read the file content. The execution result is abcdefuplint (fp. tell () # view the cursor location. The cursor is in the last fp. seek (0) # move the cursor to the initial position print (fp. tell () # move the cursor to the initial position and view the cursor's position fp. seek (2) # move the cursor to the 2nd-bit print (fp. tell () # move the cursor to the initial position and view the cursor location. The cursor is in the second position fp. seek (0, 2) # move the cursor to the End of print (fp. tell () # After moving the cursor to the initial position, view the cursor location. The cursor is at the end.

Truncate (size) Intercepts content of the specified length:

Fp = open('file.txt ', 'r +') When file.txt file content is abcdefuplint (fp. tell () # fp. truncate () # If no size is specified, the file content fp is cleared. truncate (3) # input size, which indicates that three characters are truncated from 0, and other characters are cleared. seek (0) print (fp. read () # The execution result is abc.

With usage. After opening a file, you can disable it manually. If the file is not operated, it is automatically disabled as follows:

# With usage: open (File Name) as alias. The default open mode is r mode with open('file.txt ') as fp: print (fp. read ())

Use with to open multiple files as follows:

with open('file.txt') as fp, open('a.txt') as fw:    for line in fp:        print(line)    print(fw.readlines())

There are two ways to modify a file: one is to read all the content of the file into the memory, and then empty the original file content and re-write the new content; the second is to write the modified file content to a new file:

First:

Fp = open('file.txt ', 'a +') fp. seek (0) res = fp. read () # The returned result type is a string, and the pointer is at the end of the fp. seek (0) # Move the pointer to the initial position fp. truncate () # Clear the file content new_res = res. replace ('A', 'Hello') # replace string a with hello, and then the new string content fp. write (new_res) # write the replaced content to the file

Second:

Import osfp = open('file.txt ', 'a +') fp. seek (0) fw = open('a.txt ', 'w') # Open the second file, specifically write the replaced file content for line in fp: # directly loop the file object, it loops through the content new_res = line of each row of the file. replace ('hello', '123') # replace "hello" with "666", and then "fw" with the new string. write (new_res) # write the modified content to the second file fp. close () and close the file. After the file is closed, you cannot read and write the fw.close( OS .remove('file.txt ') to delete the file OS .replace('a.txt', 'file.txt ') # Replace the new file name with the deleted file name.
import oswith open('file.txt') as fp, open('a.txt', 'w') as fw:    for line in fp:        new_res = line.replace('666', 'hello')        fw.write(new_res)os.remove('file.txt')os.replace('a.txt', 'file.txt')
The following table lists 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 ([sizehint])

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 sizhint 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])

Specifies the size of the captured bytes. The default value is the current file location.

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.