Python: Close Files If You’re Going To Open Them
I've been trying to archive some videos off Youtube lately, using yt-dlp. It's an amazing tool, but my target files have been episodes in parts. Usually four parts and Plex really hates jogging through... so what to do? Combine the files together with ffmpeg. The code was meant to be pretty simple (and 98% of it was written by ChatGPT... whoops)...
def concat_episodes(episode_name, concat_files): plfile = "file_list.txt" f = open(plfile, "w", encoding="utf-8") for filename in concat_files: f.write("file '" + filename + "'\r\n") concat_command = f"ffmpeg -stats -safe 0 -f concat -i {plfile} -c copy '{episode_name}'" print(concat_command) subprocess.run(concat_command, shell=True)
But no amount of wrangling would get ffmpeg to work. The concat filter kept throwing: Invalid data found when processing input. No amount of "-safe 0", relative paths or absolute paths worked! No permissions... no cwds or shell arguments. If I let the python script drop to the shell, then the same line pasted (since I printed it out) worked perfectly fine! What the?
OH RIGHT. I missed the memo that I should be closing a file so that it lands on disk... prior to trying to open it in another process!:
def concat_episodes(episode_name, concat_files): plfile = "file_list.txt" f = open(plfile, "w", encoding="utf-8") for filename in concat_files: f.write("file '" + filename + "'\r\n") f.close() concat_command = f"ffmpeg -stats -safe 0 -f concat -i {plfile} -c copy '{episode_name}'" print(concat_command) subprocess.run(concat_command, shell=True)
The file was still open and not flushed to disk... so ffmpeg would always open an empty file! This has been a public service announcement.