python创建文本文件的简单方法

2020-10-10 0 181

python open() 函数以指定模式打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

w 模式表示打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。    

write() 方法用于向文件中写入指定字符串。在文件关闭前或缓冲区刷新前,字符串内容存储在缓冲区中,这时你在文件中是看不到写入的内容的。

实现代码:

#!/usr/bin/python
# -*- coding:utf-8 -*-
file = open(\'C:/Users/Administrator/Desktop/a/b.txt\',\'w\')
file.write(\'你好,\\n  世界。\')

结果:

python创建文本文件的简单方法

打开这个文本可以看到内容成功写入。

python创建文本文件的简单方法

知识点扩充:

Python批量修改文本文件内容的方法

Python批量替换文件内容,支持嵌套文件夹

import os
path=\"./\"
for root,dirs,files in os.walk(path):
for name in files:
#print name
if name.endswith(\".html\"):
#print root,dirs,name 
filename=root+\"/\"+name
f=open(filename,\"r\")
filecontent=\"\"
line=f.readline() 
while line:
l=line.replace(\":/arcgis_js_api\",\"/arcgisapi\")
filecontent=filecontent+l
line=f.readline()
f.close()
f=file(filename,\"w\")
f.writelines(filecontent)
f.close()

以上就是python创建文本文件的简单方法的详细内容,更多关于python怎么创建文本文件的资料请关注自学编程网其它相关文章!

遇见资源网 Python python创建文本文件的简单方法 http://www.ox520.com/26920.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务