Python21_ file read and write

python files to read and write compatible and C

Reading file

process:

1. 打开文件

2. 读文件内容

3. 关闭文件

open a file

  • open(path, flag[, encoding][, errors])

Parameters are all strings

path: the path to the file you want to open

flag: opening file

r   以只读的方式打开文件,文件的描述符放在文件的开头
r+  打开一个文件用于读写,文件必须存在
w   打开一个文件只用于写入,如果该文件已经存在,会覆盖,不存在则创建新文件
w+ 打开一个文件用于读写,文件不存在就创建一个
a	追加
a+	读写,如果该文件已存在,则打开时会是追加模式,如果没有就创建
rb  以二进制格式打开一个文件用于只读,文件的描述符放在文件的开头
wb  以二进制格式打开一个文件用于只写入2进制
ab	以二进制格式追加
rb+
wb+
ab+
ps:硬盘上真正存储的为二进制文件

encoding: encoding, utf-8 is used and gbk

errors: error handling, it is not commonly used treatment

path = "file1.txt"
f = open(path,"r", encoding="utf-8", errors="ignore")	#f指向打开的文件
#后面两参数可以不写

Reading file

  • Read the entire contents of the file
path = "file1.txt"
f = open(path,"r", encoding="utf-8", errors="ignore")

#法一,一次读完
str1 = f.read() #适合读文件比较小的

#法二,读取指定字符数
str2 = f.read(10)
print(str2)

#法三,读取整行,包括"\n"字符

str3 = f.readline()

#法四,读取指定字符数
str4 = f.readline(10)   #读取10个字符

#法五,读取所有行并返回列表,如果指定了参数,如果指定参数大于0,则返回实际size字节的行数,及时上很少传参
lsit5 = f.readlines([size])

#关于文件的读,是一直往后读。eg:没读一个字符,就往后移动一个字符

Write file

f.write(要写入的字符串)	

在写文件时,如果要实现在写入的文件中换行,则在字符串末尾添加"\n"即可。(有的系统是"\r\n"

Position changes descriptor

f.seek(0)
f.seek(offset, from)	
#offset:右为正,左为负
#from:0:表示文件的开头,1:表示当前位置,2:表示文件的结尾

f.tell()	#能够告诉我们程序读到了哪个位置

Close the file

f.close()

A complete process

try:
    f1= open(path,"r",encoding="utf-8")	#通常写入中文的时候需要指定编码格式
    print(f1.read())
finally:
    if f1:
        f1.close()
        
#简洁写法,不用自己关闭文件,with即自动关闭文件
with open(path,"r", encoding="utf-8") as f2:
    print(f2.read())

coding

Common encoding: GBK, Unicode (length coding, etc.), UTF-8 (variable length coding)

bytes_gbk = "张三".encode("GBK")
print(bytes_gbk)
print(type(bytes_gbk))

bytes_utf8 = "张三".encode("UTF-8")
print(bytes_utf8)
print(type(bytes_utf8))

str = bytes_gbk.decode("GBK")
print(str)

str = bytes_utf8.decode("UTF-8")
print(str)

Guess you like

Origin blog.csdn.net/qq_34873298/article/details/89685557
Recommended