首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在python中从txt文件中删除某个单词的代码

在Python中,可以使用以下代码从txt文件中删除某个单词:

代码语言:txt
复制
def remove_word_from_file(file_path, word):
    with open(file_path, 'r') as file:
        lines = file.readlines()

    with open(file_path, 'w') as file:
        for line in lines:
            updated_line = line.replace(word, '')
            file.write(updated_line)

这段代码定义了一个名为remove_word_from_file的函数,它接受两个参数:file_path表示txt文件的路径,word表示要删除的单词。

首先,使用open函数以只读模式打开txt文件,并使用readlines方法读取文件的所有行,将其存储在lines列表中。

然后,再次使用open函数以写入模式打开txt文件,并使用write方法逐行写入更新后的内容。在每一行中,使用replace方法将要删除的单词替换为空字符串,从而实现删除操作。

注意:这段代码会直接修改原始的txt文件,请谨慎使用。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

检测地址能否打开[python] 原

import urllib.request   import time   opener = urllib.request.build_opener()   opener.addheaders = [('User-agent', 'Mozilla/49.0.2')]   #这个是你放网址的文件名,改过来就可以了   # file = open('test.txt')   # lines = file.readlines()   aa=['http://www.baidu.com/','http://www.baidu.com']   # for line in lines:   #     temp=line.replace('\n','')   #     aa.append(temp)   # print(aa)   print('开始检查:')   for a in aa:       tempUrl = a       try :           opener.open(tempUrl)           print(tempUrl+'没问题')       except urllib.error.HTTPError:           print(tempUrl+'=访问页面出错')           time.sleep(2)       except urllib.error.URLError:           print(tempUrl+'=访问页面出错')           time.sleep(2)       time.sleep(0.1)

01
领券