python如何编辑文档
原创Python中可以使用open()
函数和write()
方法编辑文档,下面是一个示例代码:
with open('example.txt', 'w') as f: f.write('Hello, World!')
上述代码将创建一个名为example.txt
的新文档,并向其中写入文本Hello, World!
。
如果要编辑现有文档,可以使用read()
方法读取文档内容,然后对其进行修改,最后使用write()
方法将修改后的内容写回文档,以下是一个示例代码:
with open('example.txt', 'r') as f: content = f.read() content = content.replace('World', 'Python') with open('example.txt', 'w') as f: f.write(content)
上述代码将读取名为example.txt
的现有文档,将其中的文本World
替换为Python
,然后将修改后的内容写回文档。
使用open()
函数和write()
方法编辑文档时,需要指定打开文件的模式,在上面的示例中,我们使用'w'
模式创建和写入新文档,使用'r'
模式读取现有文档,然后使用'w'
模式将修改后的内容写回文档。
上一篇:python 如何引入time 下一篇:python如何单据运行