Day2笔记(2)

文件读写:r,w,a,r+,w+,a+

f = open(r'笔记.txt',encoding='utf-8')

result = f.read()#获取文件内容

print(result)

f.close()

f = open('test.txt','w',encoding= 'utf-8')

f.write('aaa')
f.close()

#一种是读模式r,一种是写模式w,只能写,不能读,清空以前的内容
#一种是追加模式,a,不会清除当前内容
#r,读模式,只能读,不能写,打开不存在的会报错
#w,写模式,只能写不能读,会覆盖文件以前的内容,文件不存在会创建
#a,追加模式,在原来文件的内容上增加新内容,文件不存在会创建,只能写不能读

#r+,读写模式,
#w+,写读模式
#a+,追加读模式
#只要是和r有关的,打开不存在的文件都会报错
#只要和w模式有关,都会清空原来的文件
#a+文件指针默认值在末尾的,如果想读到内容,默认移动文件指针在前面


f = open('test1.txt','w', encoding= 'utf-8')
f.write('aaa111')

f.close()
f=open('test.txt',encoding='utf-8')
print(f.readline())#读取一行的内容
print(f.readlines())   #
是换行符,加r是不要转译,原字符的意思
f.seek(0)#移动文件指针
print(f.read())
f.close()

l= ['a
','b
']
f = open('liuzhao.txt','w',encoding= 'utf-8')
f.writelines(l)#ch#传一个list的话,他会帮你自动循环,把list里面每一个元素写到文件里
f.close()

打开文件不用关闭的方式:

with open('test1.txt') as f,open('test2.txt') as f2:
    f= f.read()
    f2.write('xxx')

两种修改文件的方式:

#1简单直接粗暴
f=open('test1.txt','a+',encoding='utf-8')
f.seek(0)
result =f.read()
contest = result.replace('aaa112','aaa222')#替换
f.seek(0)
f.truncate()#清空文件内容
f.write(contest)
f.close()

f2 = open('test1.txt','w')
f2.write(contest)

#第二种
#1、逐行处理
f=open('test1.txt',encoding='utf-8')
f2 = open('test2.txt','w',encoding='utf-8')

for line in f:
    result = line.upper()
    f2.write(result)
f.close()
f2.close()

import os
os.remove('test1.txt')
os.rename('test2.txt','test1.txt')
原文地址:https://www.cnblogs.com/lz523/p/10952506.html