Python 读写文本(open)

读写参数

Character Meaning
‘r’ open for reading (default)
‘w’ open for writing, truncating the file first
‘a’ open for writing, appending to the end of the file if it exists
‘b’ binary mode
‘t’ text mode (default)
‘+’ open a disk file for updating (reading and writing)
‘U’ universal newline mode (for backwards compatibility; should not be used in new code)

读写参数组合

模式 描述
rt 读取文本,默认模式
rb 读取二进制数据
wt 写入文本
wb 写入二进制
r+ 不清空原文件,读写
w+ 清空原文件,并读写
a+ 在文件末尾读写

示例

首先在左面新建一个”abc.txt”的文件,文件的内容入如下:
I
love
CSDN

只读

只读模式(默认模式)

>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","r")
>>>>print(f.read())
I
love
CSDN
>>>>f.close()

只写

写入模式

>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","w")
>>>>f.write("test")
>>>>f.close()

输出的结果是:
test

在使用”w”模式时,python会把原来的文件给覆盖掉,形成新的文件,这里注意如果写入的文件不存在,python会自动新建一个文件。

追加

追加模式

>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","a")
>>>>f.write("test")
>>>>f.close()

输出的结果是:
I
love
CSDNtest

二进制读写

另外我们还可以设定读取和写入的方式:
以二进制方式读取:

>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","rb")
>>>>print(f.read())
>>>>f.close()
b'I\r\nlove\r\nCSDN'

with实例

import re
with open("C:/Users/Administrator/Desktop/abc.txt","r",encoding="utf-8") as f:
    text=f.read()
text=re.sub(r"In \[.*\]:\n","[In]:",text)
text=re.sub(r"Out\[.*\]:","[Out]:",text)
with open("C:/Users/Administrator/Desktop/abc.txt","w",encoding="utf-8") as f:
    f.write(text)

编码问题

将一个gbk文件转码为utf8文件.注意r,w模式只能开启一种,所以encoding就确保了是编码还是解码,在r的模式下encoding做的是decode,而在w模式下encoding做的是encode.如果使用r+或者w+encoding既做decode又做encode,而且decodeencode编码相同.

gbk = open("./gbk.txt", "r", encoding = "gbk")

gbk_text = gbk.read()

gbk.close()


utf = open("./gbk.txt", "w", encoding = 'utf8')

utf.write(gbk_text)

utf.close()

open()

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

参数 说明
file 文件路径
mode rwabt
buffering
encoding 只有在tmode下有用,指定编码和解码,默认使用系统的编码格式(win下是gbk,linux是utf8)
errors
newline 指定换行符
closefd
opener

file object

方法 描述
close() 关闭流
closed 如果已经关闭则返回true
readable() 是否可读
read() (str)读取整个文本为一个字符串
readline(size=-1) (str)返回一行,size可以指定多行
readlines(hint=-1) (list),读取所有行
seek(offset[, whence]) 更改指针偏移量
tell() 返回当前流的位置
writable() 是否可写
writelines(lines) 写入一行
write(s) 写入字符串

你可能感兴趣的:(python,基础)