7天玩转Python(五)使用Python处理文件

该博客主要介绍了Python中的文件操作,包括文件的创建、读取、写入、删除、复制、重命名以及文件内容的搜索和替换。详细说明了使用open()函数打开和创建文件的不同模式,还介绍了按行、多行和一次性读取文件的方法,以及文件写入、删除等操作的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

文件通常用于存储数据或应用系统的参数。

文件的创建

文件的打开和创建可以使用open()函数。

r:以只读的方式打开文件

r+:以读写的方式打开文件

w:以写入的方式打开文件,先删除文件原有的内容,再重新写入新的内容。如果文件不存在,则创建一个新的文件。

w+:以读写的方式打开文件,先删除文件原有的内容,再重新写入新的内容。如果文件不存在,则创建一个新的文件。

a:以写入的方式打开文件,在文件的末尾追加新的内容。如果文件不存在,创建一个新的文件。

a+:以读写的方式打开文件,在文件的末尾追加新的内容。如果文件不存在,则创建一个新的文件。

文件处理一般分为以下三个步骤:

(1)创建并打开文件,使用file()函数返回一个file对象

(2)调用file对象的read(),write()等方法处理文件

(3)调用close()关闭文件,释放file对象占用的资源。

#创建文件
context = "hello python"
f = open('hello.txt',  'w')    # 打开文件
f.write(context)               # 把字符串写入文件
f.close()

文件的读取

按行读取的方式readline()

readline()每次读取文件中的一行,需要使用永真表达式循环读取文件。但当文件指针移动到文件末尾时,依然使用readline()读取文件将会出现错误。因此程序中需要添加一个判断语句,判断文件指针是否移动到文件尾部,并且通过该语句中断循环。

f = open("hello.txt")
while True:
 line = f.readline()
 if line:
     print(line)
 else:
     break
f.close()

多行读取文件readlines()

f = open("hello.txt")
lines = f.readlines()
for line in lines:
    print(line)
f.close()

一次性读取read()

f = open("hello.txt")
context = f.read()
print(context)
f.close()

通过控制read()参数,返回指定字节的内容。

f = open("hello.txt")
context = f.read(5)      # 读取文件前五个字节的内容
print(context)
print(f.tell())          # 返回文件对象当前指针位置
context = f.read(5)      # 继续读取五个字节内容
print(context)
print(f.tell())          # 输出文件当前指针位置
f.close()

file对象内部将记录文件指针的位置,以便下次操作。只要file对象没有执行close()方法,文件指针就不会释放。

文件的写入

writelines()操作

f = open("hello.txt",  "w+")
f.writelines("hello python,hello china")
f.close()
f = open("hello.txt",  "a+")
f.writelines("hi python,hi china")
f.close()

writelines()写文件的速度更快。写少量字符串可以使用write()

文件的删除操作

文件的删除操作需要使用os模块和os.path模块。文件的删除操作需要调用remove()函数实现。删除文件之先需要判断文件是否存在,存在则删除,否则不进行任何操作。

import os
if os.path.exists("hello.txt"):
    os.remove("hello.txt")

文件的复制

文件的复制需要使用write()和read()方法。

src = open('hello.txt', 'w')
src.write("hello python!hello world!")
src.close()

src = open("hello.txt", "r")
dst = open("hello2.txt", "w")
dst.write(src.read())
src.close()
dst.close()

文件的重命名

os模块的rename()函数可以对文件或目录进行重命名。

import os
li = os.listdir(".")    #listdir()返回当前目录的文件列表,"."表示当前目录
print(li)
if "hello.txt" in li:
    os.rename("hello.txt", "hi.txt")

修改文件的后缀名需要使用rename()函数,和字符串查找的函数

# 修改文件后缀名
import os
files = os.listdir(".")
for filename in files:
    pos = filename.find(".")
    if filename[pos+1:] == "txt":
        newname = filename[:pos+1]+"html"
        os.rename(filename,newname)

文件内容的搜索和替换

#文件的查找
import re
file = open("hello.txt", "r")
count = 0
for s in file.readlines():
    print(s)
    li = re.findall("hello", s)
    print(li)
    if len(li) > 0:
        count = count + li.count("hello")
    print("hello的个数{}".format(count))
file.close()
#文件的替换  把hello.txt里的hello改为hi写入hello2.txt
f1 = open("hello.txt", "r")
f2 = open("hello2.txt", "w")
for s in f1.readlines():
    f2.writelines(s.replace("hello", "hi"))
f1.close()
f2.close()

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EmbodiedTech

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值