擅长:python、mysql、java
<p>你的方法是一个很好的起点。根据您正在读取的文件类型及其内容(未指定),有几种方法可能有效:</p>
<ol>
<li>在使用整数值调用函数之前,请将其转换为带有<a href="https://docs.python.org/3/library/stdtypes.html#str" rel="nofollow noreferrer">^{<cd1>}</a>的字符串:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>check_if_string_in_file(file_name, str(123))
</code></pre>
<p>请注意,如果您的文件有类似“12345”的行,那么这种方法就不适用,因为<code>'123' in '12345'</code>是真的。您可以通过使用更严格的检查(而不仅仅是<code>in</code>)来解决这个问题</p>
<ol start=“2”>
<li>如果您知道文件中的所有行都是数字,则可以在使用<code>int</code>函数读取该行后将其转换为数字:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>def check_if_string_in_file(file_name, number_to_search):
with open(file_name, 'r') as read_obj:
for line in read_obj:
line_as_int = int(line.strip())
if number_to_search == line_as_int:
return True
return False
</code></pre>
<p>如果您计划进行几次这样的检查,那么一次将整个文件读入一个列表,然后检查列表中的目标可能是有意义的</p>