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.

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 encoding (as given by locale.getpreferredencoding(False) in Python).

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}'

see also

last updated on .