How do I write a .txt file with the same name as the input file?

Viewed 110

I provide a video as an input to my system, it processes the video and then it writes some information into a .txt file. How do I name the .txt file exactly the same as the video file name?

    # getting input video
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--input", required=True,
                    help="path to input video")
    ap.add_argument("-o", "--output", required=True,
                    help="path to output video")
    
    args = vars(ap.parse_args())
    
    # capturing the video frames from input video
    vs = cv2.VideoCapture(args["input"])

    # writing the output folder and txt file
    
    outputfile_dir = os.path.join(os.getcwd(),'output')
    if not os.path.exists(outputfile_dir):
        os.makedirs(outputfile_dir)
        os.chmod(outputfile_dir , 0o777)
    outputFilename=os.path.join(outputfile_dir,"demofile.txt")
1 Answers
from pathlib import Path


def to_txt(filename: Path) -> Path:
    """Changes a filename for an arbitrary
    file to a filename with a *.txt suffix.
    """
    
    return filename.parent / f'{filename.stem}.txt'


filename = Path('dir1/videos/my_video-12.avi')
txt_file = to_txt(filename)
print(txt_file)

Explanation

pathlib is part of Python's standard library and provides object-oriented access to path-like objects. I.e. you can hadle file and directory paths as objects with methods and properties for common operations on those types of objects. For further details, read the docs.

What the function to_txt() does is, it takes such a path-like object, namely the path to the video file as input. It then extracts the paths to the video's parent directory by accessing the property filename.parent, which returns another pathlib.Path object to the directory containing the file. So for any file named dir1/videos/my_video-12.avi, this part returns dir1/videos.

You can access a pathlib.Path's file name without the leading directories and without its suffix via the property Path.stem. In the f-string f'{filename.stem}.txt', we access this property and concatenate it with our new suffix '.txt', so that for any file named dir1/videos/my_video-12.avi, this part returns my_video-12.txt.

As you can see, what we're missing is the path to the folder containing the file, which we extracted earlier. By using the / operator, we can join pathlib.Path objects with other pathlib.Path, or as in this case, with str objects, so that the result will be a pathlib.Path object with the full path to the file on the right hand side of /. Which leaves us with dir1/videos/my_video-12.txt.

Related