pythonconfigparser

Change value in Ini to empty using Python configparser


I want to read the config file if the value is empty

Example: To convert a video file to audio file

# config.ini
[settings]
videofile = video.avi
codesplit = -vn
outputfile = audio.mp3

Output

['ffmpeg.exe', '-i', 'video.avi', '-vn', 'audio3.mp3']

If you make the value "codesplit" empty, the code will not work. example : To convert a video avi file to video mp4

[settings]
videofile = video.avi
codesplit = 
outputfile = videoaudio.mp4

Output

['ffmpeg.exe', '-i', 'video.avi', '', 'videoaudio.mp4']

I want to remove this quote so that the code to works

 '',

full code

import subprocess
import configparser


config = configparser.ConfigParser(allow_no_value=True)
config.read(r'config.ini')
videofile = config.get('settings', 'videofile')
outputfile = config.get('settings', 'outputfile')
codesplit = config.get('settings', 'codesplit', fallback=None)



ffmpeg_path = r"ffmpeg.exe"


command = [
    f"{ffmpeg_path}",
    "-i", (videofile),
    (codesplit),
    (outputfile),]

process = subprocess.Popen(
    command,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    bufsize=1,
    universal_newlines=True)
process.communicate()

print(command)

Solution

  • You can try using an if-else statement to check if there is a codesplit option passed from the config file or not.

    import subprocess
    import configparser
    
    
    config = configparser.ConfigParser(allow_no_value=True)
    config.read(r"config.ini")
    videofile = config.get("settings", "videofile")
    outputfile = config.get("settings", "outputfile")
    codesplit = config.get("settings", "codesplit", fallback=None)
    
    
    ffmpeg_path = r"ffmpeg.exe"
    
    if codesplit:
        command = [
            f"{ffmpeg_path}",
            "-i",
            (videofile),
            (codesplit),
            (outputfile),
        ]
    else:
        command = [
            f"{ffmpeg_path}",
            "-i",
            (videofile),
            (outputfile),
        ]
    
    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,
        universal_newlines=True,
    )
    process.communicate()
    
    print(command)
    

    This code checks if codesplit is there in the config. If so, it adds it to the command list. If not, it doesn't.

    The output looks like

    ['ffmpeg.exe', '-i', 'video.avi', 'videoaudio.mp4']
    

    where the empty string is absent.