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

被折叠的 条评论
为什么被折叠?



