0

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?

Fly
  • 810
  • 2
  • 9
  • 28

1 Answers1

1

The easy fix is to prefix the string with b, so that it is treated as a byte 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:
    ...
Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69