Python's path to growth: article 1 (5) basic operations on files,

Source: Internet
Author: User

Python's path to growth: article 1 (5) basic operations on files,
I. Ternary operations

The if, else, and we learned in the previous chapter have a simple method.

Its Expression is like this: Variable = value 1 if condition else value 2

Ii. Concept of category

Class is the core of object-oriented programming. It plays the container role of relevant data and logic. They provide the ability to create "real"
The blueprint of the object (that is, the instance. For Python, everything is an object, and objects are created based on classes.

Iii. File Operations

How does python operate files? Let's take a look at it. Generally, there are several types of read/write operations on files.

Open Function

Complete list of open files in different modes:

Mode Description

R

Open the file in read-only mode. The file pointer will be placed at the beginning of the file. This is the default mode.

Rb

Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file.

R +

Open a file for reading and writing. The file pointer will be placed at the beginning of the file.

Rb +

Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.

W

Open a file for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.

Wb

Open a file in binary format for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.

W +

Open a file for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file.

Wb +

Open a file in binary format for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file.

A

Open a file for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing.

AB

Open a file in binary format for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing.

A +

Open a file for reading and writing. If the file already exists, the file pointer is placed at the end of the file. When the file is opened, the append mode is used. If the file does not exist, create a new file for reading and writing.

AB +

Open a file in binary format for append. If the file already exists, the file pointer is placed at the end of the file. If the file does not exist, create a new file for reading and writing.

(1) open a file

Foo = open ('test', 'R') # open is the keyword, test is the name of the file, and r is the read-only mode.
print(foo)

<_ Io. TextIOWrapper name = 'test' mode = 'R' encoding = 'cp936 '>

Oh? What is returned? After opening the file, the foo value is equal to an iterator, which is a way to access elements in the set. The iterator object is accessed from the first element of the set until all elements are accessed. The iterator cannot be rolled back and can only be iterated forward.

So how can we see the content in it? Very simple

(2) Load file content to memory

Read () function:

foo = open('test','r')
foo = foo.read()
print(foo)

You only need foo to be equal to foo. read (). The read function reads a string from an open file.

It is said that some people do not like the read method to read files !! What is this?

Because:

The read () mechanism is to read the file content into the memory, which does not meet your needs.

Therefore, readlines () loads all the content to the memory at a time, splits the content by row, and merges the list.

Readlines ()

foo = open('test','r')
ss = foo.readlines()
print(ss)
['a\n', 'bb\n', 'ccc\n', 'dddd\n', 'eeeee']
Nana \ n is Mao, oh it turns out that it was a line break to scare Lao Tzu, some people said that I would read 1 GB files in 1 MB of memory, didn't you want my life, python has another way to process files.
readline()
Read Only one row of data at a time, so that we can perform a for loop and exit after processing the content to be processed.
foo = open('test','r+')
ss = foo.readline()
dd = foo.readline()
print(ss+dd)

A
Bb

(3) reading Chinese files

Some diligent students tried it. Why does Nima report an error in Chinese files? In fact, it's not your mistake but the encoding problem.

① Encoding and decoding

For the Chinese file encoding format is gbk, so under normal circumstances we use Pycharm for debugging is the uft-8 encoding format, so it will report an error

② Python2.7 and 3.5

These methods are mainly used to convert encoding into UTF-8.

Python2.7:

Method 1:Create a txt file with windows in the pycharm project directory

foo = open('ttt.txt','r')
ss = foo.read().decode('gbk')
print ss

I
2nd
3, 3, 3
4th 4th 4th
5-5, 5-5
Sixty-sixty

Python3.5:

0.0 is it depressing that he does not need to change the encoding.

foo = open('ttt.txt','r')
ss = foo.read()
print (ss)
 
The focus of codecs functions is:
Whether it is 2.7 or 3.5, if Chinese characters cannot be output in some special cases, we use the codecs function.
After the codecs function is called:
In fact, the method is very simple. The hormone codecs function also provides the open method. You only need codecs. open ('filename ', 'open mode', 'encoding format.
Note:
Confusion may occur when switching between 2.7 and 3.5 using pycharm. The actual test is recommended.
 
(4) write operations
Python provides many open methods, but few r, r +, w, w +,, a + Let's take a look at ① r +. what's in front of me !!, Well, all of them are replaced. (We recommend that you use linu for testing. After all, it is running in linux)
② W. All the contents before Khan were replaced, so w + will not need to be tested.
③ A. It is appended to the end, so it is not a line break! Add \ n in front.
(5) Delete
Python does not provide the ability to directly delete file content, so it can only be judged by statements (I don't know)
Example: If it is really troublesome, you can use with to optimize it and I will explain it. First, open the file. for, if the content of for is equal to ccc \ n, nothing will be done, otherwise, add \ n to the list because there is a line break. Use w + to open the file and write the content in the list.
1 foo = open ('text', 'R') 2 aa = foo. readlines () 3 ccc = [] 4 for I in aa: 5 if I = 'ccc \ N': 6 continue 7 else: 8 ccc. append (I) 9 foo. close () 10 11 foe = open ('text', 'W + ') 12 for iss in ccc: 13 foe. write (iss) 14 foo. close ()
Delete

 

(6) attributes of the file object
The following lists all attributes related to the file object:
Example:
Fo = open ("foo.txt", "r +") print "file name:", fo. nameprint "Disabled:", fo. closedprint "Access Mode:", fo. modeprint "whether to add spaces at the end:", fo. softspace
Result:
File Name: foo.txt disabled: False access mode: whether to add a space: 0 to the end of wb
(7) File Location

As you can see in the above open mode list there is such a word 'pointer ', then this pointer is similar to the cursor position, so in python, there is this positioning operation

Original file text

aaa
bbb
ddd
fff

① Open the file. Why is only aaa bb output here? It is because a pointer is added to read (), pointing to 6, so this is output, some people also asked why we should output three B in 6. Why are we two now? In fact, it's because your sister has another line break.

1 foo = open ('text', 'r + ') 2 aa = foo. read (6) 3 print (aa) 4 aaa 5 bb
File Location-open a file
② Find the current location tell ()
foo = open('text','r+')
aa = foo.read(3)
ss = foo.tell()
print(aa,ss)
③ Re-locate the pointer to the beginning of the file
1 foo = open ('text', 'r + ') 2 aa = foo. read (3) 3 print (foo. tell () 4 print (aa) 5 foo. seek (0, 0) 6 print (foo. tell () 7 3 8 aaa 9 0
Reposition the pointer

 

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.