File overwrite confirmation with option that takes a file object as an argument with Python argparse

Motivation

The command line parser argparse included in the python standard library allows you to specify a file object as the argument type. it can. (ʻArgparse.FileType`) It's very convenient because you don't have to create a file object from a string.

However, even if the write mode (mode ='w') is specified, it will open automatically without saying whether it is present or not, so for a sloppy person, the file is unintentionally overwritten and the contents are erased. There is a risk and it is very dangerous. Therefore, I implemented file overwrite confirmation, so make a note so that you do not forget how to do it.

Implementation example.

An example implemented in my work pdf_merge_multipages by referring to the method of the site mentioned at the end of the sentence.

pdf_merge_multipages.py(Excerpt)



class FileTypeWithCheck(argparse.FileType):

    def __call__(self, string):
        if string and "w" in self._mode:
            if os.path.exists(string):
                sys.stderr.write(('File: "%s" exists. Is it OK to overwrite? [y/n] : ') % (string))
                ans = sys.stdin.readline().rstrip()
                ypttrn = re.compile(r'^y(es)?$', re.I)
                m = ypttrn.match(ans)
                if not m:
                    sys.stderr.write("Stop file overwriting.\n")
                    sys.exit(1)
                    # raise ValueError('Stop file overwriting')
            if os.path.dirname(string):
                os.makedirs(os.path.dirname(string),
                            exist_ok=True)
        return super(FileTypeWithCheck, self).__call__(string)

    def __repr__(self):
        return super(FileTypeWithCheck, self).__repr__()

....

....

def main():
    argpsr = argparse.ArgumentParser(description='Merge multiple mages in PDF files w/o gap.')
    argpsr.add_argument('inputs', metavar='input-file', type=argparse.FileType('rb'),
                        nargs='+', help='Input PDF file(s)')
    argpsr.add_argument('-output', metavar='filename', type=FileTypeWithCheck('wb'),
                        nargs=1, help='Output file', dest='output', default='a.out.pdf')

...
...

def main():
    argpsr = argparse.ArgumentParser(description='Merge multiple mages in PDF files w/o gap.')
    argpsr.add_argument('inputs', metavar='input-file', type=argparse.FileType('rb'),
                        nargs='+', help='Input PDF file(s)')
    argpsr.add_argument('-output', metavar='filename', type=FileTypeWithCheck('wb'),
                        nargs=1, help='Output file', dest='output', default='a.out.pdf')

...
...

if __name__ == '__main__':
    main()

If the file exists and you avoid overwriting, you may have to choose between exiting the script (ʻexit () ) or throwing an exception. In the above example, ʻexit () is used, but if the file was opened in read mode with the argument of ʻinputs` earlier, the script may end without closing it. The point where the sex remains is a little caught.

Reference material

Recommended Posts

File overwrite confirmation with option that takes a file object as an argument with Python argparse
Create an exe file that works in a Windows environment without Python with PyInstaller
Format when passing a long string as an argument of python
Create an Excel file with Python3
Get the formula in an excel file as a string in Python
A script that retrieves tweets with Python, saves them in an external file, and performs morphological analysis.
Extract lines that match the conditions from a text file with python
The eval () function that calculates a string as an expression in python
Creating a simple PowerPoint file with Python
[Python] A program that creates stairs with #
Quickly create an excel file with Python #python
A typed world that begins with Python
I made a configuration file with Python
Create an application that inputs, displays, and deletes forms by using an array as a DB with Python / Flask.
How to read a CSV file with Python 2/3
Create an app that guesses students with python
[Python] Make a game with Pyxel-Use an editor-
Create a page that loads infinitely with python
Create a Photoshop format file (.psd) with python
Lambda expression (correction) that creates an index (dictionary with members as keys) of the members of the object being collected in python
Read line by line from a file with Python
I want to write to a file with Python
Open a file dialog with a python GUI (tkinter.filedialog)
Insert an object inside a string in Python
A python script that imports a dated csv file into BigQuery as a time partition table
[Python] You can save an object to a file by using the pickle module.
A memo that uses an interactive display mode like Jupyter notebook with VSCode + Python
Don't take an instance of a Python exception class directly as an argument to the exception class!
[Python] If you create a file with the same name as the module to be imported, an Attribute Error will occur.
A script that takes a snapshot of an EBS volume
A tool that makes a standalone jar an executable file
A server that echoes data POSTed with flask / python
A memo that I touched the Datastore with python
Python: Get a list of methods for an object
Run a Python file with relative import in PyCharm
[Python] Create a Tkinter program distribution file with cx_Freeze
Create a 2d CAD file ".dxf" with python [ezdxf]