Python使用subprocess更新文件内容

来源:互联网 发布:人工智能技术有哪些 编辑:程序博客网 时间:2024/06/05 11:36

在使用Python处理文件时,一个常见的需求就是修改某个文件的内容。注意到,我们可以直接在一个文件末尾添加新的内容,却无法直接修改或删除一个文件中已经存在内容。需要一定的方法才能实现这样的目的。我们使用subprocess库为例,来实现一个用于更新文件内容的函数。

该函数将输入文件中第一次出现的“hello world”及其之后的内容全部删除。

import subprocessdef update_file_content(filepath):    cmd = 'mv -f %s %s' % (filepath, filepath+'~')    subprocess.check_output(cmd, shell=True)    with open(filepath+'~', 'rb') as f:        cont = f.read()    with open(filepath, 'wb') as f:        f.write(cont[0:cont.find('hello world')])    cmd = 'rm -r %s' % filepath+'~'    subprocess.check_output(cmd, shell=True)
原创粉丝点击