Search code examples
pythonjupyter-notebookbzip2

Passing python variable into the shell


I have a folder, say myFolder, in which there are multiple csv files and I want to bzip2 them. One option is of course to use shell:

bzip2 myFolder/file1.csv

How can I do it (same command) in jupyter notebook?

I tried:

for x in os.listdir("myFolder"):
    sourceFile = 'myFolder/'+x
    !bzip2 sourceFile

which returns

bzip2: Can't open input file sourceFile: No such file or directory.


Solution

  • for x in os.listdir("myFolder"):
        sourceFile = 'myFolder/'+x
        !bzip2 {sourceFile}
    

    Passing Python variables into the shell–is possible using the {varname} syntax