If I get the content of a file with ret = os.read(fd, os.path.getsize(file))
, how do I check if ret
contains a specific string, for example "hello world"
?
An answer on here was simply if "hello world" not in ret:
, but this does not work anymore in python 3.4, apparently (Because of mixing bytes with unicode or something). How do I do this now?
The easy fix is to prefix the string with b
, so that it is treated as a b yte string:
if b"hello world" not in ret:
However I strongly recommend you to use the builtin open()
and file objects, as described on the Python I/O tutorial .
On Python 3, strings returned by file objects are always unicode strings by default, so that you don't have to bother about byte strings and encodings.
Here is a working example:
with open(file_name) as f:
file_content = f.read()
if 'hello world' not in file_content:
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.