5-python文件操作

1.打开文件

当传参顺序不一致时,不能使用位置传参,应使用关键字传参
open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

通常使用:
open(file=“”,mode=“”,encoding=“”)
(1)file:(所在路径)文件名
(2)mode:打开文件的模式
①只读r:默认模式,可省略
②写入w:若原文件存在,会删除原文件的内容,重新开始编辑;如果文件不存在,会创建新文件
③追加a:原文件内容不会被删除,可以在后面写入新的内容;如果文件不存在,会创建新文件
(3)encoding:编码格式
默认为UTF-8,某些情况下可省略,但建议注明。常见的编码有UTF-8、GBK、Big5

2.文件读取

(1)read(num)方法:从文件中读取指定字节num的数据,如果num为空默认全部读入

例如:在D盘有一个hello.txt的文件

在这里插入图片描述

打开并读取
如果多次使用read(num),会从上次读取结束的位置继续往后读取num个字节,如果上次已经读到底,再调用read将读不到任何数据

f=open(file="D:/hello.txt",mode="r",encoding="UTF-8")
print(f.read())

在这里插入图片描述

(2)readlines()按照行的方式把整个文件中的内容进行一次性读取,返回一个列表,其中每一行的数据为一个元素

在这里插入图片描述

f=open(file="D:/hello.txt",mode="r",encoding="UTF-8")
print(f.readlines())

在这里插入图片描述

(3)readline()方法:调用一次只会读取到一行
在这里插入图片描述

f=open(file="D:/hello.txt",mode="r",encoding="UTF-8")
print(f.readline())
print(f.readline())
print(f.readline())

在这里插入图片描述

(4)使用for循环读取

在这里插入图片描述
每次调用都会读取一行的内容

f=open(file="D:/hello.txt",mode="r",encoding="UTF-8")
for x in f:
    print(x)

在这里插入图片描述

3.文件关闭

使用结束后使用close关闭文件对象,结束对文件的占用
如果不使用close,文件会在程序结束运行时关闭
文件未关闭时,相当于文件已打开,不能在计算机上对文件进行删除、重命名等操作

f=open(file="D:/hello.txt",mode="r",encoding="UTF-8")
f.close()
print(f.read()) # ValueError: I/O operation on closed file.

操作完成后自动关闭文件 with open,不再需要close操作

with open(file="D:/hello.txt",mode="r",encoding="UTF-8") as f:
    print(f.read()) # 输出见下图
print(f.read()) # ValueError: I/O operation on closed file.

在这里插入图片描述

[练习] 统计D:/practice.txt(下图)中单词"and"出现的次数

在这里插入图片描述
[解]
法一:使用read读取,count计数

f=open("D:/practice.txt","r")
print(f.read().count("and")) 
f.close()

输出:11
此方法统计的是文中出现"and”的次数,而非"and”单词的数量

在这里插入图片描述

法二:使用for循环读取
此方法能准确统计到"and”单词出现的次数

count=0 # 记录单词"and"出现的次数
f=open("D:/practice.txt","r")
for x in f: # 每次读取一行
    x=x.strip() # 去除开头和结尾的空格和换行符
    words=x.split(" ") # 以空格切割字符串,形成一个个单词存入words
    for y in words:
        if y=="and":
            count+=1
print(count)

输出:10

4.文件写入/追加

f.write(“写入内容”):写入内存缓冲区
f.flush():真正写入文件(追加需要,写入不需要)

在这里插入图片描述
(1)追加

f=open("D:/hello.txt","a") # 追加打开,不可读
f.write("nihao")
f.flush() # 必须有
f.close()

在这里插入图片描述
追加打开不可读,需要重新只读读打开

f=open("D:/hello.txt","a") # 追加打开,不可读
f.write("nihao")
f.flush()
print(f.read()) # io.UnsupportedOperation: not readable
f=open("D:/hello.txt","a") # 追加打开,不可读
f.write("nihao")
f.flush()
f=open("D:/hello.txt","r") # 只读
print(f.read()) # hahanihao

换行追加

在这里插入图片描述

f=open("D:/newfile.txt","a")
f.write("\nhello")
f.close()

在这里插入图片描述

(2)写入
写入可以不使用flush,会自动调用

D盘无文件

f=open("D:/newfile.txt","w") # 创建新文件newfile.txt
f.write("newwrite")
f.close()

在这里插入图片描述
在此基础上覆盖写入

f=open("D:/newfile.txt","w")
f.write("nihao")
f.close()

在这里插入图片描述

同样,写入操作也不能读取

[练习] 将D盘下test.txt文件的内容的正式项拷贝到D盘下bill.txt的文件中

在这里插入图片描述

fold=open("D:/test.txt","r",encoding="UTF-8") # 老文件用fold标识,只读即可
fnew=open("D:/bill.txt","w",encoding="UTF-8") # 新文件用fnew标识,这里用的是写入w
for x in fold: # 遍历每一行
    x=x.strip()
    if x.split(",")[3] == "测试":  # 分割结果用列表保存,可以进行下标索引
        continue
# 等价于 word=x.split(",");  if word[3]...
    fnew.write(x+"\n")
fold.close()
fnew.close()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45825865/article/details/129950568