创建和打开文件
open()方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用这个函数,如果该文件无法被打开,会抛出OSError错误。
使用open()方法一定要保证关闭文件对象,即调用close()方法。
open()函数常用形式是接收两个参数:文件名(file)和模式(mode)
#读取指定字符串
with open("d:\\PmStudy\wenjian.txt","r",encoding="utf-8") as file:
string = file.read(3) #读取前面三个,不写数字代表读取全部
print(string)
#读取文件中的部分内容
with open("d:\\PmStudy\wenjian.txt","r",encoding="utf-8") as file:
file.seek(2) #从第二个字符开始读
string = file.read(4)
print(string)
#读取文件中的一行数据
with open("d:\\PmStudy\wenjian.txt","r",encoding="utf-8") as file:
number=0
while True:
number+=1
line=file.readline()
if line=="":
break
print(number,line,end="\n")
#读取文件中的所有行
with open("d:\\PmStudy\wenjian.txt","r",encoding="utf-8") as file:
message=file.readlines() #读取所有行
print(message)