Home >Backend Development >Python Tutorial >Detailed explanation of how to read and write Python files and set file character encoding

Detailed explanation of how to read and write Python files and set file character encoding

巴扎黑
巴扎黑Original
2017-08-18 13:56:192514browse

File reading and writing operations are an important and commonly used part in various programming languages. Today, let’s talk about python’s file reading and writing operations in detail, as well as the points that need attention.

1. Open the file in python

The code is as follows:

f = open("d:\test.txt", "w")

Instructions:

The first parameter is the file name, including the path;

The second parameter is the open mode mode

'r': read-only (default. If the file does not exist, an error is thrown)

'w': write-only ( If the file does not exist, the file is automatically created)

'a': Append to the end of the file

'r+': Read and write

If you need to open the file in binary mode, You need to add the character "b" after mode, such as "rb", "wb", etc.

2. Python reads the file content f.read([size])

The parameter size means reading The quantity to be taken can be omitted. If the size parameter is omitted, it means reading the entire contents of the file.

f.readline() reads the contents of one line of the file f.readlines() reads all the lines into the array [line1, line2,…lineN].

f = open('./pythontab.txt', 'r')
content = f.read()
print content

This method is often used to avoid loading all file contents into memory to improve efficiency.

3. Python writes to the file f.write(string)

Write a string to the file

f = open('./pythontab.txt', 'r+')
f.write('Hello, Pythontab.com')
f.close()

Note: If the writing ends, you can follow the string Add "\n" to indicate a newline, and finally the file must be closed with f.close(). Otherwise exceptions may occur, especially in high concurrency situations.

4. Positioning the content in the file

After f.read() reads, the file pointer reaches the end of the file. If f.read() is used again, it will be found that what is read is Empty content. If you want to read the entire content again, you must move the positioning pointer to the beginning of the file:

f.seek(0)

The format of this function is as follows (unit is bytes): f .seek(offset, from_what) from_what represents the starting position of reading, and offset represents a certain amount of movement from from_what. For example, f.seek(10, 3) represents positioning to the third character and moving back 10 characters.

When the from_what value is 0, it indicates the beginning of the file. It can also be omitted. The default is 0, which is the beginning of the file. A complete example is given below:

f = open('./pythontab.txt', 'r+')
f.write('Hello, Pythontab.com')
f.seek(5)     # 定位到第6个byte
f.read(1)        
f.seek (-3, 2) #定位到第2个字符并再向前移动3个字符
f.read(1)

5. Close the file

Close the file to release resources. After the file operation is completed, be sure to remember to close the file f.close() to release resources for other programs. It is relatively simple to read and write files in ASCII or gbk encoding format. The reading and writing are as follows:

# coding=gbk
f = open('./pythontab.txt','r') # r 指示文件打开模式,即只读
s1 = f.read()
s2 = f.readline()
s3 = f.readlines() #读出所有内容
f.close()
f = open('./pythontab.txt','w') # w 写文件
11 f.write(s1)
12 f.writelines(s2) # 没有writeline
13 f.close()

6. f.writelines will not output newlines

Python unicode file reading and writing:

# coding=gbk
import codecs
f = codecs.open('./pythontab.txt','a','utf-8')
f.write(u'中文')
s = '中文'
f.write(s.decode('gbk'))
f.close()
f = codecs.open('./pythontab.txt','r','utf-8')
s = f.readlines()
f.close()
for line in s:
    print line.encode('gbk')

7. Encoding of python code files

The default py file is ASCII encoding. When Chinese is displayed, a conversion from ASCII to the system default encoding will occur. At this time, an error will occur: SyntaxError: Non -ASCII character. You need to add encoding instructions in the first or second line of the code file:

# coding=utf-8 ##Storage Chinese characters in utf-8 encoding

print 'Chinese' like above The string input directly is processed according to the encoding of the code file. If unicode encoding is used, there are the following two methods:

s1 = u'中文' #u means using unicode encoding to store information

s2 = unicode('Chinese','gbk')

unicode is a built-in function, and the second parameter indicates the encoding format of the source string.

decode is a method that any string has, which converts the string into unicode format. The parameter indicates the encoding format of the source string.

encode is also a method that any string has, converting the string into the format specified by the parameter.

Encoding of python strings

Use u'Chinese character' to construct a unicode type, otherwise it will construct a str type

The encoding of str is related to the system environment , usually the value obtained by sys.getfilesystemencoding()

So to convert from unicode to str, you need to use the encode method

To convert from str to unicode, you need to use decode

For example :

# coding=utf-8   #默认编码格式为utf-8
s = u'中文' #unicode编码的文字
print s.encode('utf-8')   #转换成utf-8格式输出 
print s #效果与上面相同,似乎默认直接转换为指定编码

Summary:

u=u'unicode encoded text'

g=u.encode('gbk') #Convert to gbk format

print g #This is garbled code because the current environment is utf-8 and gbk encoded text is garbled

str=g.decode('gbk').encode('utf-8') #Use gbk The encoding format reads g (because it is gbk encoded) and converts it to utf-8 format for output

print str #Normal display of Chinese

Safe method:

s .decode('gbk','ignore').encode('utf-8′) #Read in gbk encoding (of course, read text in gbk encoding format) and ignore the wrong encoding, convert to utf-8 encoding Output

Because the function prototype of decode is decode([encoding], [errors='strict']), you can use the second parameter to control the error handling strategy. The default parameter is strict, which means an illegal event is encountered. character;

If set to ignore, illegal characters will be ignored;

If set to replace, illegal characters will be replaced with ?;

If set For xmlcharrefreplace, XML character references are used.

The above is the detailed content of Detailed explanation of how to read and write Python files and set file character encoding. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn