python中open与write中w用法

本文详细介绍了如何使用Python的open函数创建和写入文件,包括如何批量创建多个文件并写入相同内容,以及如何进行简单的文本内容过滤和替换。通过实例演示了在指定路径下创建文件、写入内容和关闭文件的过程。

open函数

open函数可以打开一个文件,当路径下没有文件的时候,也可以创建一个文件;
在这里插入图片描述
现在D:\python_1路径下是空的,我们创建一个名字为hello的文件,需要加上参数’w’;

open('D:/python_1/hello.txt','w')

在这里插入图片描述
在这里插入图片描述

write函数

write是写入使用,例如我吗要在hello文件中写入‘hello python’

f = open('D:/python_1/hello.txt','w')
f.write('hello python')

在这里插入图片描述
我们可以看到内容已经写入

我们可以创建一个模块,在D:/python_1/目录下创建hello0到hell10一共十个文件,并且输入内容为“hello python”

def file_hello(name,msg,n):
    desktop_path = 'D:/python_1/'
    #设置文件路径
    n = int(n)
    #将字符串类型n更改为整数类型
    for i in range(n):
        #循环并且设定i的取值范围小于n
        desktop_path_name = desktop_path + name + str(i) + '.txt'
        #设置完整的路径与文件名
        desktop = open(desktop_path_name, 'w')
        #创建并且打开文件,w方式打开会覆盖文件原有内存
        desktop.write(msg)
        #在文件中写入内容
        desktop.close()
        #关闭文件
        print(i+1)
        #打印这是创建的第几个文件

file_hello('Hello','Hello python','10')

在这里插入图片描述
在这里插入图片描述

def text_cresate(name,mgg):
    desktop_path = 'D:/python_1/'
    #文件夹的位置
    full_path = desktop_path + name + '.txt'
    #文件完整的路径
    file = open(full_path,'w')
    #打开一个文件名字为变量(full_path)的文件,如果有就打开,没有就创建,并且会覆盖原有内容
    file.write(mgg)
    file.close()
    print('Done')

def text_filter(word,censored_word = 'lame',changed_word = 'Awesome'):
    #censored_word代表word中要替换的关键词,cheanged_word代表word中被替换的词替换成什么
    return word.replace(censored_word, changed_word)
    #返回word替换后的样子

def censord_changed():
    name = input('请输入要创建的文件的名字:')
    msg = input('请输入文件内容:')
    msg = text_filter(msg)
    #进行内容筛选
    text_cresate(name,msg)
    #创建文件

censord_changed()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值