f=open(‘python.txt’,‘r’,encoding=“UTF-8”)
读操作相关的方法
read(num):num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,表示读取文件中所有的数据。
readlines():readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素。
readline():一次读取一行。
for line in f:可通过for循环一行一行读取文件。
close:关闭打开的文件。
with open:通过with open打开的文件可以操作完可以自动关闭。
# 打开文件
f = open("D:/quiz.txt","r",encoding="UTF-8")
# 读取文件:read(num)
print(f.read())
# 关闭文件重新打开,不然下面受上一个读取影响打开为空
f.close()
f = open("D:/quiz.txt","r",encoding="UTF-8")
# 读取文件:readlines()
print(f.readlines())
# 关闭文件重新打开,不然下面受上一个读取影响打开为空
f.close()
f = open("D:/quiz.txt","r",encoding="UTF-8")
# 读取文件:readline()
print(f.readline())
# 关闭文件重新打开,不然下面受上一个读取影响打开为空
f.close()
f = open("D:/quiz.txt","r",encoding="UTF-8")
# 可用for循环输出每一行
for line in f:
print(line)
# 关闭文件重新打开,不然下面受上一个读取影响打开为空
f.close()
f = open("D:/quiz.txt", "r", encoding="UTF-8")
# 通过with open打开的文件可以操作完可以自动关闭
with open("D:/quiz.txt", "r", encoding="UTF-8") as f:
f.read()
# 打开文件,一个不存在的文件。注意:当打开的文件不存在,会直接创建,如果存在会直接清空
f = open("D:/write.txt","w",encoding="UTF-8")
# write写入文件
f.write("quiz write.")
# flush刷新内容
f.flush()
# close关闭文件
f.close()
open(“D:/write.txt”,“a”,encoding=“UTF-8”)
其他操作与w模式文件的写入一致,只是a模式与w模式打开文件时不会清空文件。
# 打开文件,一个存在的文件。注意:a模式打开当打开的文件不存在,会直接创建,如果存在不会清空
f = open("D:/write.txt","a",encoding="UTF-8")
# write写入文件
f.write("quiz write.")
# flush刷新内容
f.flush()
# close关闭文件
f.close()