Search code examples
snakemake

snakemake: write files from an array


I have an array xx = [1,2,3] and I want to use Snakemake to create a list of (empty) files 1.txt, 2.txt, 3.txt.

This is the Snakefile I use:

xx = [1,2,3]
rule makefiles:
    output: expand("{f}.txt", f=xx)
    run:
        with open(output, 'w') as file:
            file.write('blank')

However instead of having three new shiny text files in my folder I see an error message:

expected str, bytes or os.PathLike object, not OutputFiles

Not sure what I am doing wrong.


Solution

  • Iterate output to get filenames and then write to them. See relevant documentation here.

    rule makefiles:
        output: expand("{f}.txt", f=xx)
        run:
            for f in output:
                with open(f, 'w') as file:
                    file.write('blank')
    

    Rewriting above rule, to parallelize, by defining target files in rule all:

    rule all:
        expand("{f}.txt", f=xx)
    
    rule makefiles:
        output: 
            "{f}.txt"
        run:
            with open(output[0], 'w') as file:
               file.write('blank')