1.使用open(文件路径,打开方式,编码)函数读取文件中的内容
open(filepath):打开文件
open(filepath,'r'):打开方式,默认是读取
open(filepath,'[打开方式,比如'r']'):
r w a:读取、写入、追加
r+ w+ a+:都是读取写入,方式不同
r+:如果文件不存在,则报错,写入时是覆盖写入
w+:如果文件不存在,新建文件;写入时是清空写入
a+:如果文件不存在,新建文件;写入时是追加写入
open(filepath).read():读取文件中的内容
open(filepath).readline():读取文件中一行的内容
open(filepath).readline()[1]:读取文件中的内容,返回值是列表。
open(filepath).close():关闭文件
open(filepath).seek(0):将光标回到首位
with open()函数,不用close()方法,默认自动关闭,所以需要制定一些规则.
with open(filePah,'w+') as file1,open(filePah,'w+') as file2:
file1.write(a)
file2.write(b)
print(file1.read())
print(file2.read())
2.文件内建函数和方法
文件内建函数和方法:
open(): 打开文件
read():输入
readline():输入一行
seek():文件内移动
write():输出
close():关闭文件
#写入
file1=open('name.txt','w')
file1.write('诸葛亮')
file1.close()
#读取
file2=open('name.txt')
print(file2.read())
file2.close()
#写入
file1=open('name.txt','a+')
file1.write('\n关飞')
file1.close()
#读取一行
file2=open('name.txt')
print(file2.readline()) #返回的内容:1、诸葛亮
file2.close()
#循环读取每一行
file3=open('name.txt')
for i in file3.readlines():
print(i)
file3.close()