如何删除python中包含特定字符串的行
我有一个像这样的文本文件如何删除python中包含特定字符串的行,python,string,Python,String,我有一个像这样的文本文件 Big:house small:door Big:car Small:chair Big:plane 如何删除包含单词“big”的行,使其看起来像这样,但我不想一起创建一个新文件 small:door small:chair 这是我的尝试 with open('QWAS.txt','r') as oldfile: for line in oldfile: if bad_words in line: newfile.write(line) 试
Big:house
small:door
Big:car
Small:chair
Big:plane
如何删除包含单词“big”的行,使其看起来像这样,但我不想一起创建一个新文件
small:door
small:chair
这是我的尝试
with open('QWAS.txt','r') as oldfile:
for line in oldfile:
if bad_words in line:
newfile.write(line)
试试这个:
newfile = r'output.txt'
oldfile = r'input.txt'
with open(newfile, 'w') as outfile, open(oldfile, 'r') as infile:
for line in infile:
if if line[:5].lower() == 'small':
outfile.write(line)
#output
small:door
Small:chair
当然,这假设您希望删除冒号左侧的小行或小行。此外,您将有一个新的文件输出,因为我认为您不想更新您的输入文件。我们可以这样做:
with open('QWAS.txt','r+') as f:
data = ''.join([i for i in f if not i.lower().startswith('big')]) #1
f.seek(0) #2
f.write(data) #3
f.truncate() #4
您可以尝试使用正则表达式
import re
oldfile = open('QWAS.txt','r')
newfile = open('newfile.txt','w')
for line in oldfile:
if re.search('[Ss]mall',line):
newfile.write(line)
oldfile.close()
newfile.close()
它给出了输出文件“newfile.txt”
如果你只是把每一行不小的内容都写进一个新文件“newfile2.txt”
如果行是
small:Big
,或notbig:small
,该怎么办?最简单的方法是将整个文件读入内存(可能使用file.readlines()
)读入列表),在那里进行调整,然后将结果写回文件。如果文件无法放入内存,则会变得有点困难。在这种情况下,创建一个新文件就容易多了。@kindall你能给我举个例子吗,任何东西都可以搜索“python原地编辑文件”并找到fileinput模块。好了。如果你在这里展示的事实上是你写的所有东西,那就很有意义了。你知道错误告诉你的是什么吗?在OP中:“我不想一起创建一个新文件”。此外,如果您试图将newfile
和oldfile
设置为同一个文件,这将完全删除您的文件!请记住,您可以使用第[:5]行。lower()==“small”好的捕捉。。。那就更好了,我怎么才能把每一行没有小的内容都写进一个新文件呢?如果我从一个像myword=linecache.getline('Test.txt',1)@HellosAddme这样的文件中抓取一些东西呢?
small:door
Small:chair
import re
oldfile = open('QWAS.txt','r')
newfile = open('newfile.txt','w')
newfile2 = open('newfile2.txt','w')
for line in oldfile:
if re.search('[Ss]mall',line):
newfile.write(line)
else:
newfile2.write(line)
oldfile.close()
newfile.close()
newfile2.close()