![](/img/trans.png)
[英]How to check a .txt file for text and give an error message if blank
[英]Python - How to check if the text is in a file txt?
我有一个检查文本是否在file.txt
的功能。
该函数的工作方式如下:如果文件中包含文本,则文件将关闭。 如果文本不包含在文件中,则将其添加。
但这是行不通的。
import urllib2, re
from bs4 import BeautifulSoup as BS
def SaveToFile(fileToSave, textToSave):
datafile = file(fileToSave)
for line in datafile:
if textToSave in line:
datafile.close()
else:
datafile.write(textToSave + '\n')
datafile.close()
urls = ['url1', 'url2'] # i dont want to public the links.
patGetTitle = re.compile(r'<title>(.*)</title>')
for url in urls:
u = urllib2.urlopen(url)
webpage = u.read()
title = re.findall(patGetTitle, webpage)
SaveToFile('articles.txt', title)
# so here. If the title of the website is already in articles.txt
# the function should close the file.
# But if the title is not found in articles.txt the function should add it.
您可以像这样更改SaveToFile
函数
您的title
是列表,而不是字符串,因此您应该像这样将其命名为SaveToFile('articles.txt', title[0])
以获取列表的第一个元素
def SaveToFile(fileToSave, textToSave):
with open(fileToSave, "r+") as datafile:
for line in datafile:
if textToSave in line:
break
else:
datafile.write(textToSave + '\n')
笔记:
即)
for i in []:
print i # This will print nothing since it is iterating over empty list same as yours
list
而不是一个string
因为re.findall
返回了一个列表对象,您必须将列表的第一个元素传递给函数。 for..else
,如果循环未正确终止,则else情况将起作用。 即)
for i in []:
print i
else:
print "Nooooo"
输出:
Nooooo
您应该将SaveToFile函数重构为这样。
def SaveToFile(fileToSave, titleList):
with open(fileToSave, 'a+') as f:
data = f.read()
for titleText in titleList:
if titleText not in data:
f.write(titleText + '\n')
f.close()
此函数读取文件的内容(如果存在或创建的话),并检查textToSave是否在文件内容中。 如果找到textToSave,则关闭文件,否则将内容写入文件。
只需使用r+
模式,如下所示:
def SaveToFile(fileToSave, textToSave):
with open(fileToSave, 'r+') as datafile:
if textToSave not in datafile.read():
datafile.write(textToSave + '\n')
关于该文件模式,来自以下答案 :
``r+'' Open for reading and writing. The stream is positioned at the
beginning of the file.
而且re.find_all()
总是返回一个列表,因此,如果您尝试编写列表而不是字符串,则会出现错误。
因此,您可以使用:
def SaveToFile(fileToSave, textToSave):
if len(textToSave) => 1:
textToSave = textToSave[0]
else:
return
with open(fileToSave, 'r+') as datafile:
if textToSave not in datafile.read():
datafile.write(textToSave + '\n')
这似乎更接近您的问题。
这将检查文件中的文本是否:
def is_text_in_file(file_name, text):
with open(file_name) as fobj:
for line in fobj:
if text in line:
return True
return False
如果文本不在文件中,则使用上面的功能进行检查并将文本写入文件的末尾。
def save_to_file(file_name, text):
if not is_text_in_file in (file_name, text):
with open(file_name, 'a') as fobj:
fobj.write(text + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.