pypyr.steps.fileread permalink

read file into context permalink

Load a file into the the pypyr context.

fileread works like this:

- name: pypyr.steps.fileread
  comment: read file in into context
    in:
      fileRead:
        path: path/to/file.ext # path to file
        key: arb # save file contents to this context key
        binary: False # Optional. Default False. Set True to read file as bytes.
        encoding: utf-8 # Optional. Default None (platform default).

If path is relative, it resolves relative to the current working directory.

If you set binary to True, the file contents will read as bytes without any decoding. When binary is False (the default), the file contents will decode use the platform-dependant default encoding.

fileread does not do any parsing of the file’s contents at the time of reading. If you want to parse json, toml or yaml, check out fetchjson, fetchtoml & fetchyaml.

read file as text permalink

Here is an example showing to read file contents as text in the default encoding and then using the contents in subsequent steps in the pipeline:

- name: pypyr.steps.fileread
  comment: read file as text and save contents to txt1
  in:
    fileRead:
      path: testfiles/my-file.txt
      key: txt1

# some arbitrary steps using the contents written to txt1
- name: pypyr.steps.echo
  in:
    echoMe: '{txt1}'

- name: pypyr.steps.echo 
  in:
    echoMe: from text {txt1} file

substitution expressions permalink

All inputs support substitutions. This means that you can construct the path or key partly or entirely from other context variables:

  - name: pypyr.steps.set
    comment: set some arbitrary values in context
    in:
      set:
        filename: my-file
        thekey: mykey

  - name: pypyr.steps.fileread
    comment: use substitution expressions for path and key
    in:
      fileRead:
        path: testfiles/{filename}.txt
        key: '{thekey}'

binary mode permalink

Set binary to True to returns a bytes object from the file without any decoding:

- name: pypyr.steps.fileread
  comment: read file in binary mode as bytes & save contents to mykey.
  in:
    fileRead:
      path: testfiles/my-file.bin
      key: mykey
      binary: True

- name: pypyr.steps.echo
  comment: the binary data is now in mykey.
  in:
    echoMe: '{mykey}'

encoding permalink

By default in text mode the file will read in the platform’s default encoding. This is utf-8 for most systems, but be aware on Windows it’s still cp1252.

You can use the encoding input explicitly to set the encoding:

- name: pypyr.steps.fileread
  comment: set encoding
  in:
    fileRead:
      path: testfiles/utf8-example.txt
      key: mykey
      encoding: utf-8

See here for more details on handling text encoding in pypyr and changing the defaults.

You cannot set encoding in binary mode.

See here for a list of available encodings.

see also

last updated on .