python【文件操作】

一、创建文件夹

  • 判断文件或者文件夹是否存在
import os

path=r'D://测试文件夹'
if not os.path.exists(path):
    os.mkdir(path)
    print(os.path.exists(path))

二、文件操作模式

1.覆盖写入

file.close(file = open("test.txt", 'w')
#写入内容
file.write("hellow word")
#关闭文件
file.close())

2.读取

python中读取文件的方法,read() readlines()

file = open("test.txt", 'r')
#读取文件内容
msg = file.read()
print(msg)
#关闭文件
file.close()

readlies()读取文件内容,以列表形式返回

file = open("test.txt", 'r')
#读取文件内容
msg = file.readlines()
print(msg)
#关闭文件
file.close()

3.追加

在末尾文本之后,写入

with open("test.txt", "a") as f:
    f.write("This is additional content.\n")

三、 Python脚本在文件中查找和替换文本

def find_replace(file_path, search_text, replace_text):
    with open(file_path, 'r') as f:
        text = f.read()
        modified_text = text.replace(search_text, replace_text)
    with open(file_path, 'w') as f:
        f.write(modified_text)

四、 python清空文件夹

import os
import stat
def del_files(path):
    for root, dirs, files in os.walk(path, topdown=False):
        print(root)  # 各级文件夹绝对路径
        print(dirs)  # root下一级文件夹名称列表,如 ['文件夹1','文件夹2']
        print(files)  # root下文件名列表,如 ['文件1','文件2']
        # 第一步:删除文件
        for name in files:
            os.chmod(os.path.join(root, name), stat.S_IWRITE)  # 更改什么吊没权限
            os.remove(os.path.join(root, name))  # 删除文件
        # 第二步:删除空文件夹
        for name in dirs:
            os.rmdir(os.path.join(root, name))  # 删除一个空目录

path = "D://测试文件夹"
del_files(path)
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值