search
HomeBackend DevelopmentPython TutorialDetailed explanation of how to read and write Python files and set file character encoding

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
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)