文件的访问
使用 open() 函数 打开文件 ,返回一个 file 对象
使用 file 对象的读 / 写方法对文件进行读 / 写的 操作
使用 file 对象的 close() 方法关闭文件
打开文件
open()方法,需要一个字符串路径,并返回一个文件对象,默认是”读模式”打开
语法如下:
fileobj=open(filename[,mode[,buffering]])
helloFile=open("F:\example\hello.txt")
读取文件
read()方法,不设置参数将整个文件的内容读取为一个字符串,可以设置最大读入字符数来限制read()函数一次读取大小,如read(10)
fileContent = helloFile.read()
helloFile.close()
print(fileContent)
readline()方法,从文件中获取一个字符串,每个字符串就是文件中的每一行;还有readlines()方法
fileContent=""
while True:line=helloFile.readline()if line=="": # 或者 if not linebreakfileContent+=line
helloFile.close()
print(fileContent)