How to read standard input or variable files at the same time like paste command in Python

It is a good practice to use the with statement when opening a file in Python. However, opening variable files at the same time with this syntax is not straightforward. Of course, it doesn't work even if I write it like this.

with [open(fn) for fn in file_names] as files:

For example, when performing processing such as the paste command, simultaneous open is absolutely necessary. So, in this article, I'll write about how to use the with statement to achieve behavior like the paste command in Python.

Use the contextlib module!

paste.py


import argparse
import contextlib


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('fs', nargs='*', type=argparse.FileType(),
                        default='-')
    parser.add_argument('--delimiter', default='\t')
    args = parser.parse_args()

    with contextlib.ExitStack() as stack:
        for f in args.fs:
            stack.enter_context(f)
        paste(args.fs, args.delimiter)


if __name__ == "__main__":
    main()

The behavior when type = argparse.FileType (), default ='-' is specified in ʻadd_argument ()is [this article](https://qiita.com/hi-asano/items/010e7e3410ea4e1486cb) As you can see in. And this time, by combining it withnargs ='*'`, you can get a list of file objects from variable command line arguments.

And what I want to convey most is the part of this with sentence. In the first place, the with statement is used to wrap the execution of a block with the method of "context manager". And the module to easily implement this context manager type is contextlib.

To handle variable files with a with statement like this one, first create a context manager with ʻExitStack () and add the objects you want to manage with ʻenter_context (). With this, close is called firmly when exiting the with block.

implementation of paste

Deviating from the purpose of this article, here is an implementation example of paste ().

from itertools import zip_longest


def rstrip(x):
    if x is None:
        return ''
    else:
        return x.rstrip()


def paste(files, delimiter):
    for lines in zip_longest(*files):
        stripped = map(rstrip, lines)
        print(delimiter.join(stripped))

Digression

Q13 of 100 language processing knocks is also OK with this code

Recommended Posts

How to read standard input or variable files at the same time like paste command in Python
[Python] How to open two or more files at the same time
How to read text by standard input or file name specification like cat in Python
How to get the files in the [Python] folder
How to get a list of files in the same directory with python
How to get the variable name itself in python
How to measure processing time in Python or Java
How to debug the Python standard library in Visual Studio
In the python command python points to python3.8
[sh] How to store the command execution result in a variable
How to check the memory size of a variable in Python
How to judge that the cross key is input in Python3
How to display bytes in the same way in Java and Python
How to read CSV files in Pandas
[Python] Add comments to standard input files
How to hide the command prompt when running python in visual studio 2015
How to get the date and time difference in seconds with python
How to input a character string in Python and output it as it is or in the opposite direction.
How to pass the execution result of a shell command in a list in Python
How to use the C library in Python
How to generate a QR code and barcode in Python and read it normally or in real time with OpenCV
How to receive command line arguments in Python
How to embed a variable in a python string
How to implement Discord Slash Command in Python
Summary of how to import files in Python 3
How to read all the classes contained in * .py in the directory specified by Python
How to read time series data in PyTorch
Turn multiple lists with a for statement at the same time in Python
How to output "Ketsumaimo" as standard output in Python
How to unit test a function containing the current time using freezegun in python
[Note] How to write QR code and description in the same image with python
How to retrieve the nth largest value in Python
[For beginners] How to use say command in python!
How to download files from Selenium in Python in Chrome
How to add page numbers to PDF files (in Python)
How to use the model learned in Lobe in Python
[Python] How to output the list values in order
Steps to change table and column names in your Django model at the same time
How to calculate the sum or average of time series csv data in an instant
What seems to be a template of the standard input part of the competition pro in python3
How to pass the execution result of a shell command in a list in Python (non-blocking version)
How to switch the configuration file to be read by Python
[Go language] How to get terminal input in real time
How to run a Python file at a Windows 10 command prompt
How to use the __call__ method in a Python class
Change the standard output destination to a file in Python
How to import a file anywhere you like in Python
How to generate exponential pulse time series data in python
How to log in automatically like 1Password from the CLI
Allow Python to select strings in input files from folders
How to copy and paste command line content without mouse in bash on Linux or mac
Put the process to sleep for a certain period of time (seconds) or more in Python
Part 1 I wrote the answer to the reference problem of how to write offline in real time in Python
How to develop in Python
[Python] How to use input ()
Determine the date and time format in Python and convert to Unixtime
How to handle multiple versions of CUDA in the same environment
How to determine the existence of a selenium element in Python
How to know the internal structure of an object in Python
How to make a string into an array or an array into a string in Python
The 15th offline real-time how to write reference problem in Python