1.写入文件
#1.open
writeToFile = open("writeTest.txt","w",encoding="utf-8")
#2.write
writeToFile.write("学python")
#3.flush刷新文件写入硬盘,因为写入文件的数据会暂存在内存,为了计算机运算效率更高。
# writeToFile.flush()
#3.close
writeToFile.close()#close中的实现方法有flush功能,如果不再写入操作就用它
#读取文件要新建一个对象
readFile = open("writeTest.txt","r",encoding="utf-8")
print(readFile.read())
readFile.close()
2.读取文件
#1.open
file1 = open("JavaWeb的三层结构.txt","r", encoding="utf-8")
#2.read() 不传参数表示读取全部内容,如果有多个read会继承上一个read的指针位置
print("read读取的",file1.read(10)) #读取了文件的前十个字符
#3.readline() 读取一行内容
oneRow = file1.readline()
print(oneRow)
print(type(oneRow))# <class 'str'>
#4.readlines() 读取全部内容,返回一个列表
lines = file1.readlines()
print(lines) # 可以遍历输出
print(type(lines))# <class 'list'>
#5.close 关闭文件
file1.close()
# 这行代码与open的区别是,不需要用close关闭文件了
# with open("JavaWeb的三层结构.txt","r", encoding="utf-8") as file1
#小练习,读取文件中接口一词的出次数
file2 = open("JavaWeb的三层结构.txt","r",encoding="utf-8")
count = file2.read().count("接口")
print("接口一词在文件中出现了%d次" % count)# 接口一词在文件中出现了5次
3.追加内容到文件
#追加内容到文件,只需要将文件操作模式改为 a 即可,其余的和写入操作一样
# a 模式下,如果文件不存在,会自动创建文件
#1.open
writeToFile = open("writeTest.txt","a",encoding="utf-8")
#2.write
writeToFile.write("学python\n")
#3.flush刷新文件写入硬盘,因为写入文件的数据会暂存在内存,为了计算机运算效率更高。
# writeToFile.flush()
#3.close
writeToFile.close()#close中的实现方法有flush功能,如果不再写入操作就用它
#读取文件要新建一个对象
readFile = open("writeTest.txt","r",encoding="utf-8")
print(readFile.read())
readFile.close()