White learn Python (18): basic file operations

Life is short, I chose Python

The foregoing Portal

White learn Python (1): Opening

White Science Python (2): basic data type (on)

White Science Python (3): fundamental data types (lower)

White Science Python (4): Variable Basic Operation

White Science Python (5): base operator (on)

White Science Python (6): base operator (lower)

White Science Python (7): based flow control (on)

White Science Python (8): the basis of flow control (lower)

White Science Python (9): basic data structure (list) (a)

White Science Python (10): basic data structure (list) (lower)

White Science Python (11): basic data structure (tuples)

White Science Python (12): basic data structure (dictionary) (a)

White Science Python (13): basic data structure (dictionary) (lower)

White Science Python (14): basic data structure (set) (a)

White Science Python (15): basic data structure (set) (lower)

White Science Python (16): the basic data type (function) (a)

White Science Python (17): the basic data type (function) (lower)

Absolute and relative paths

Before the introduction of file operations, we first introduce two concepts of absolute and relative paths.

First look at Baidu Baidu's explanation:

  • Absolute path: refers to the absolute position of the directory, directly to the target location, usually the path from the letter began. Complete description file path location is the absolute path.
  • Relative path: the path relative path refers to the relationship with other files (or folders) from the path of the file where due.

I wonder if you did not read the students, did not understand me give you deeper under the chestnut to understand.

Absolute path

For example, we want to describe Demo.pythe absolute path, then that is: F:/project/python-learning/base-data-def/Demo.py.

relative path

Relative paths describe the path of the current position relative to the target location, such as the current path of our existence F:/project/python-learning/, we still have to that described above Demo.py, then its relative path ./base-data-def/Demo.py.

open a file

Python provides a built-in function to open a file for us open().

Common syntax:

open(file, mode='r')

The complete syntax:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Parameter Description:

  • file: Required, file path (relative or absolute path).
  • mode: Optional, the file open mode
  • buffering: a buffer
  • encoding: general use utf-8
  • errors: error level
  • newline: distinguish line break
  • closefd: Incoming file parameter types

Common mode parameter values:

mode description
t Text mode (default).
x Write mode, create a new file, if the file already exists it will error.
b Binary mode.
+ Open a file is updated (read and write).
r Open the file in read-only mode. Pointer file 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. This is the default mode. Generally used for non-text files such as pictures and so on.
r+ Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+ Opens a file for reading and writing binary format. The file pointer will be placed at the beginning of the file. Generally used for non-text files such as pictures and so on.
w Open a file for writing only. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb Open a file for writing in binary format only. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Generally used for non-text files such as pictures and so on.
w+ Open a file for reading and writing. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+ Opens a file for reading and writing binary format. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Generally used for non-text files such as pictures and so on.
a Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
ab Open a file in binary format for additional. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after 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 will be placed at the end of the file. It would append mode when the file is opened. If the file does not exist, create a new file for reading and writing.
ab+ Open a file in binary format for additional. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

Handle and a spout lip off, the following open our first example:

str1 = open('F:/project/python-learning/base-data-def/Demo.py', mode='r').read()
print(str1)

I will not print the results posted out, normal printing sample code in our previous articles.

Encoding format

Depending on the encoding format, the file can be divided into binary text characters and bytes.

We daily see are text characters, but the text characters are converted into binary bytes when stored in the computer, this time, it must take into account the problem of coding.

We look at the example of FIG conversion:

It is noteworthy that, in Python3, the default file encoding is UTF-8, commonly coded text characters are ASCII and Unicode.

Having said that, it is to see a sample code:

str2 = '好好学习,天天向上'
print(type(str2))
a = str2.encode('utf-8')
print(type(a))
print(a.decode('utf-8'))

Print results are as follows:

<class 'str'>
<class 'bytes'>
好好学习,天天向上

You can see, we'll string encode()after encoding type becomes byte.

If we use the coding gbkof a way of decoding the above what will happen?

print(a.decode('gbk'))

The results are as follows:

Traceback (most recent call last):
  File "F:/project/python-learning/base-file/Demo.py", line 10, in <module>
    print(a.decode('gbk'))
UnicodeDecodeError: 'gbk' codec can't decode byte 0x8a in position 26: incomplete multibyte sequence

Tell us can not be used gbkto decode operation.

This fact is well understood, we would like the Chinese translated into English (coding), then we want to by Japanese translation English translation back to the Chinese (decoding), then the Japanese translation will definitely call you sick mind.

OS module

Earlier we described a file operated by built-in functions, we can also OS module simpler l hey action file.

OS operating system and the module is related modules.

To demonstrate, first create a test.txtfile.

First, we open the file:

import os
os.chdir('F:/project')
file = open('test.txt')

Read and print this file:

print(file.read())

The results are as follows:

微信公众号:极客挖掘机

Then we add some content in the following:

file.write('关注公众号,好好学习,天天向上')

Then perform the incorrect report found:

Traceback (most recent call last):
  File "F:/project/python-learning/base-file/Demo.py", line 17, in <module>
    file.write('关注公众号,好好学习,天天向上')
io.UnsupportedOperation: not writable

As can be seen from the error message, the current problem is that we read permission, because when we read is read-only permissions to write, so the slightly modified the code to read files in the above:

import os
os.chdir('F:/project')
file = open('test.txt', mode='a+')
file.write(' \n 关注公众号,好好学习,天天向上')

After the execution is complete we look at our test file:

Write successfully.

We tested an interesting thing, if we read the same file twice what will happen?

import os
os.chdir('F:/project')
file = open('test.txt')
print(file.read())
print(file.read())

Print results are as follows:

微信公众号:极客挖掘机
关注公众号,好好学习,天天向上

We obviously printed twice in the code, why only show up again?

Because read()read all the contents, after reading the cursor is not content refers to studying in the final, and then again read the affirmation.

Well, the content Benpian stop here, I hope the students can practice hands-down sample code.

Sample Code

This series of small series all the code will be placed on code management repository Github and Gitee, to facilitate access.

Sample Code -Github

Sample Code -Gitee

Guess you like

Origin www.cnblogs.com/babycomeon/p/11832779.html