python文件
open()打开函数
在可以编辑文件之前,必须使用open函数打开文件。
myfile = open(“file.txt”)
open的第二个参数
open(name,mode,encoding)
name:文件名;
mode:设置打开文件的模式
r:可读
w:可写
a:追加
b:以二进制模式打开它,它用于非文本文件(如图像和声音文件)
如:
#写入模式
open(“file.txt”,“w”)
#只读模式
open(“file.txt”,“r”)
open(“file.txt”)
#二进制写入模式
open(“file.txt”,“wb”)
encoding:编码格式(推荐使用utf-8)
关闭资源
open(“file.txt”,“wb”)
file.close()
读取文件
reading files写入文件
file = open(“file.txt”,“r”)
cont = file.read()
print(cont)
file.close()
读文件
若要读取特定数量的文件,可以向读取函数提供一个参数作为参数。这决定了应该读取的字节数。
您可以在同一个文件对象上进行更多的调用,以逐字节读取文件的更多内容。在没有参数的情况下,Read返回文件的其余部分。
file = open(“file.txt”, “r”)
print(file.read(16))
print(file.read(4))
print(file.read(4))
print(file.read())
file.close()
读取行
readlines
file = open(“file.txt”, “r”)
print(file.readlines())
file.close()
还可以使用for循环来迭代文件中的行:
file = open(“file.txt”, “r”)
for line in file:
print(line)
file.close()
文件对象.readline():读取一行
文件对象.readlines():读取全部行,得到列表
for line in 文件对象:for循环文件行,一次循环得到一行数据
for line in f:
line - line.strip() #去除开通和结尾的空格以及换行符
words = line.split( " " )
for word in words:
if word == "itheima":
count +=1 #如果单词是itheima,进行数量累计加1
#判断单词出现次数并累计
print(f"itheima出现的次数是:{count}")
f.close()
写入文件
write方法
file = open(“newfile.txt”, “w”)
file.write(“写入字符串在文件里”)
file.close()
file = open(“newfile.txt”, “r”)
print(file.read())
file.close()
w模式将创建一个文件,如果它还存在
写入字节数
msg = “Hello world!”
file = open(“newfile.txt”, “w”)
amount_written = file.write(msg)
print(amount_written)
file.close()
文件不存在,会创建新的文件
文件存在,会清空原来的内容
追加写入操作
f = open(‘python.txt’,‘a’)
a模式,文件不存在会创建文件
存在会在最后,追加写入文件
使用文件
try:
f = open(“file.txt”)
print(f.read())
finally:
f.close()
内容刷新
f.flush()
当调用flush的时候,内容会真正写入文件
这样做避免频繁的操作硬盘,导致效率下降
处理文件
这样做的另一种方法是使用with语句。该变量只能在带语句的缩进块中访问。
with open(“file.txt”) as f:
print(f.read())
即使在语句中出现异常,文件也会自动在结束语句结束时关闭。(自动关闭)
with open的用法:
with open(“file.txt”) as f:
print(f.read())