#text的存储格式为每一行的字符串存储
#text文件的写入
data='尊敬的领导:\n\t您好,'#可以通过转义字符实现换行、缩进
# with open(r'./test.txt',mode='w',encoding='utf8') as tf:
# tf.write(data)
#迭代写入
list2=['尊敬的领导:\n','\t您好\n']#必须带换行符‘\n’,否则只插入一行
with open(r'./test.txt',mode='w',encoding='utf8') as tf2:
tf2.writelines(list2)
#末行追加,mode='a'表示末行追加模式,文件必须已存在
data2='我是末行追加'
with open(r'./test.txt',mode='a',encoding='utf8') as tf3:
tf3.write(data2)
#清空文件内容,适用于任何能用记事本正常打开的文件
with open(r'./test.log',mode='w',encoding='utf8') as tf2:
tf2.truncate()
#text文件的读取
#读取所有内容,返回字符串
with open(r'./test.txt',mode='r',encoding='utf8') as rf:
content=rf.read()
print(content)#尊敬的领导:\n\t您好\n我是末行追加
#按行读取,以列表形式返回每行内容(上一行以‘\n’结尾)
with open(r'./test.txt',mode='r',encoding='utf8') as rf2:
content2=rf2.readlines()
print(content2)#['尊敬的领导:\n', '\t您好\n', '我是末行追加']
#按元素读取行,-1表示读取所有行,n(n>=0)表示读取前几个元素,以列表形式返回元素所在的行
with open(r'./test.txt',mode='r',encoding='utf8') as rf3:
content3=rf3.readlines(7)
print(content3)#['尊敬的领导:\n', '\t您好\n']
#指定读取首行元素,-1表示读取整行,n(n>=0)表示读取前几个元素,返回字符串
with open(r'./test.txt',mode='r',encoding='utf8') as rf4:
content4=rf4.readline(2)
print(content4)#'尊敬'