操作系统模块:文件内容是否包含字符串x? (Python 3.4)

时间:2015-05-10 15:53:38

标签: python string python-3.x

如果我使用ret = os.read(fd, os.path.getsize(file))获取文件内容,如何检查ret是否包含特定字符串,例如"hello world"

这里的答案只是if "hello world" not in ret:,但这在python 3.4中不再有效,显然(因为将字节与unicode或其他东西混合)。我现在该怎么做?

1 个答案:

答案 0 :(得分:1)

简单的解决方法是在字符串前加b,以便将其视为 b yte字符串:

if b"hello world" not in ret:

但是我强烈建议您使用builtin open()和文件对象,described on the Python I/O tutorial

在Python 3上,默认情况下,文件对象返回的字符串始终是unicode字符串,因此您不必担心字节字符串和编码。

这是一个有效的例子:

with open(file_name) as f:
    file_content = f.read()

if 'hello world' not in file_content:
    ...