[OE-core] [PATCH 3/3] oeqa/utils/ftools: Checks before appending/reading files

Paul Eggleton paul.eggleton at linux.intel.com
Mon Oct 19 13:41:09 UTC 2015


Hi Leo,

On Monday 19 October 2015 05:24:44 leonardo.sandoval.gonzalez at linux.intel.com 
wrote:
> From: Leonardo Sandoval <leonardo.sandoval.gonzalez at linux.intel.com>
> 
> Before trying to append/read a file, check if file exists.
> 
> Signed-off-by: Leonardo Sandoval
> <leonardo.sandoval.gonzalez at linux.intel.com> ---
>  meta/lib/oeqa/utils/ftools.py | 24 ++++++++++++++----------
>  1 file changed, 14 insertions(+), 10 deletions(-)
> 
> diff --git a/meta/lib/oeqa/utils/ftools.py b/meta/lib/oeqa/utils/ftools.py
> index 64ebe3d..70a55b8 100644
> --- a/meta/lib/oeqa/utils/ftools.py
> +++ b/meta/lib/oeqa/utils/ftools.py
> @@ -8,20 +8,24 @@ def write_file(path, data):
> 
>  def append_file(path, data):
>      wdata = data.rstrip() + "\n"
> -    with open(path, "a") as f:
> +    if os.path.isfile(path):
> +        with open(path, "a") as f:
>              f.write(wdata)

Hang on - opening a nonexistent file with mode 'a' is perfectly fine, it'll just 
get created - why do we need this check?


>  def read_file(path):
>      data = None
> -    with open(path) as f:
> -        data = f.read()
> +    if os.path.isfile(path):
> +        with open(path) as f:
> +            data = f.read()
>      return data
> 
>  def remove_from_file(path, data):
> -    lines = read_file(path).splitlines()
> -    rmdata = data.strip().splitlines()
> -    for l in rmdata:
> -        for c in range(0, lines.count(l)):
> -            i = lines.index(l)
> -            del(lines[i])
> -    write_file(path, "\n".join(lines))
> +    rawdata = read_file(path)
> +    if rawdata:
> +        lines = rawdata.splitlines()
> +        rmdata = data.strip().splitlines()
> +        for l in rmdata:
> +            for c in range(0, lines.count(l)):
> +                i = lines.index(l)
> +                del(lines[i])
> +        write_file(path, "\n".join(lines))

Checking a file exists before opening it isn't good practice. It's much better 
to try opening it and if the open fails with IOError of errno.ENOENT then 
ignore it (or rather, if e.errno  != errno.ENOENT then re-raise the 
exception).

Cheers,
Paul

-- 

Paul Eggleton
Intel Open Source Technology Centre



More information about the Openembedded-core mailing list