. Python file Operations

Source: Internet
Author: User

1. Simply read the contents of the file (codecs use)

There is a 1.txt document in the current directory

To open a file:

Import Codecs

(1) Open file

f = codecs.open (' 1.txt ')

(2) file operation (read or write)

Print (F.read ())

(3) Close the file

F.close ()

The results are as follows:

650) this.width=650; "src=" Https://s5.51cto.com/oss/201710/27/88ed8dd2b331713e6ead2994b8ab2674.png "title=" 1.png " alt= "88ed8dd2b331713e6ead2994b8ab2674.png"/>

This method is equivalent to take out the entire file, as a string to use, late with regular matching, very convenient, applicable.

"Codecs this module, is open file, the introduction of this module, the purpose: To solve the file garbled." It is recommended to use this module later when reading and writing "


If you set:

Text = F.read ()

To view the type of text:

Print (type (text))

View to type is "str" (String)


Type is a string, we can use the string method:

result = Text.replace (' 1 ', ' A ')

Print (Result)



2. Write a new file

Import Codecs

f = codecs.open (' 2.txt ', ' W ')

F.write (' Hello world!\n ')

F.write (' Hello {0}!\n '. Format (' Lln '))

F.write (' You cool!\n ')

F.write (' I like it!\n ')

F.close ()

Comments:

# open (filename, mode)

# mode has several parameters:

R Read

W Write

b Binary

A append


3. Common usage of file operation

Readlins () Method:

This method reads the file, turns each line into a separate string, and puts it into a list, the first element of the first behavior list, and so on.

Example:

Import Codecs

f = codecs.open (' 1.txt ', ' RB ')

T_list = F.readlines ()

Print (T_list[0]

Print (F.readlines ())

F.close ()

return Result:

1111111111 First Row

[]

Comments:

Why does print (F.readlines ()) return an empty list?

Because the previous readlines () has read the file to the end, the next time it is read with the ReadLines () method, it will read from the end of the article, so the result is [].


ReadLine () Method:

This method, read the file, each readline () read only one row, the cursor will stay at the beginning of the next line;

When the next ReadLine () is executed, the current line is read from the cursor.

Import Codecs

f = codecs.open (' 1.txt ', ' RB ')

Print (F.readline ())

Print (F.readline ())

Print (F.readline ())

Print (F.readline ())

Print (F.readline ())

F.close ()

return Result:

1111111111

Aaaaaaaaaa

2222222222

bbbbbbbbbb

3333333333


Next () Method:

Contrast:

ReadLine () reads a row of files, returns a string

Next () reads the next line of the file to return a string


The Write () method and the Writelines () method:

Write () must pass in a (whole) string

Writelines () must pass in a sequence


Example 1:

Import Codecs

f = codecs.open (' 2.txt ', ' WB ')

F.write (' Hello lili\n cccccccc\n aaaaaaaaaa\n ') # # an integer string

F.close ()

You can see more than one file:

650) this.width=650; "src=" Https://s1.51cto.com/oss/201710/27/6507bdf01a81599da6bbac9cec4fbd81.png "title=" 2.png " alt= "6507bdf01a81599da6bbac9cec4fbd81.png"/>

File contents:

650) this.width=650; "src=" Https://s1.51cto.com/oss/201710/27/b6cc42cf2ca0d2ab0e695229fab046d1.png "title=" 3.png " alt= "B6cc42cf2ca0d2ab0e695229fab046d1.png"/>


Example 2:

Import Codecs

f = codecs.open (' 2.txt ', ' WB ')

F.writelines ([' aaaaa\n ', ' bbbbbbbb\n ', ' CCCCCCCC ']) # #传入一个列表 (sequence)

F.close ()

You can see the contents of one more file:

650) this.width=650; "src=" Https://s4.51cto.com/oss/201710/27/5cfa3041723de9997e3016db1c9f5143.png "title=" 4.png " alt= "5cfa3041723de9997e3016db1c9f5143.png"/>


Tell () Method:

Indicates which character position the current cursor falls on

Example:

Import Codecs

f = codecs.open (' 3.txt ', ' WB ')

F.writelines ([' aaaaa\n ', ' bbbbbbbb\n ', ' CCCCCCCC '])

Print F.tell ()

F.close ()

Return:

23


Seek () method:

Specifies the position of the cursor, seek (0) is moved to the beginning of the article

Example:

Import Codecs

f = codecs.open (' 3.txt ', ' WB ')

F.writelines ([' aaaaaaaaaaaaaaa\n ', ' bbbbbbbbbbbbb\n ', ' cccccccc\n '])

Print F.tell ()

F.seek (0)

F.write (' sssssssssssssssss ') # #重新写入

F.close ()

return Result:

sssssssssssssssssbbbbbbbbbbbb

Cccccccc

As seen from the result, the total length of the file is unchanged by moving the cursor to the beginning and writing the string at the beginning and replacing the character in the position corresponding to the original string.


Special usage of 4.with

Example:

Import Codecs

With Codecs.open (' 1.txt ', ' RB ') as F:

Print (F.read ())

This method does not need to write close () and automatically closes the file after execution is complete.


Expand:

Print file specifies the contents of the line:

Method One:

Import Codecs

With Codecs.open (' 1.txt ', ' RB ') as F:

For line, value in enumerate (f):

if line = = 4-1: #打印第四行的内容, subscript 3

Print (value)


Method Two: (Python has a method of its own)

Import Linecache

Count = linecache.getline (filename,linenum)


Example:

Import Linecache

Count = Linecache.getline (' 1.txt ', 4) # #下标为3

Print Count

This article is from the "Note space" blog, so be sure to keep this source http://286577399.blog.51cto.com/10467610/1976728

. Python file Operations

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.