Archive for December, 2017

convert a file to an UTF-8-encoded text

December 16, 2017 Leave a comment

I wrote a simple script that takes an input file, changes its character encoding to UTF-8, and prints the result to the screen.

It’s actually a wrapper around the Unix commands “file” and “iconv“. The goal was to make its usage as simple as possible. The script is here:


$ input.txt

The program tries to detect the encoding of the input file.


Categories: bash, python Tags: ,

work in a temp. dir. and delete it when done

December 11, 2017 Leave a comment

You want to work in a temp. directory, and delete it completely when you are done. You also need the name of this temp. folder.

You can write with tempfile.TemporaryDirectory() as dirpath:, and the temp. dir. will be removed automatically by the context manager when you quit the with block. Nice and clean.

import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as dirpath:
    fp = Path(dirpath, "data.txt")
    # create fp, process it, etc.

# when you get here, dirpath is removed recursively

More info in the docs.

Categories: python Tags: ,