INI Files: What They Are and How to Use Them

Last update: March 9th 2025
  • INI files are configuration documents that store settings for programs and applications.
  • They use a simple structure with sections, keys and values ​​to organize information.
  • They are common in software configuration, game customization, and task automation.
  • They can be read and written using various programming languages ​​such as Pascal, PHP and Python.
INI files

Welcome to our journey to unravel the mystery of the INI filesIf you've ever wondered what INI files are or how to use them effectively, you've come to the right place. These files may seem like an enigma, but with the right information, they become a powerful tool in the world of computing and software configuration. In this article, we'll thoroughly explore what INI Files are, how they work, and how you can get the most out of them.

INI Files: What do these acronyms mean?

Let's start from the beginning. What does it mean? INI in the INI Archives? These acronyms refer to «Initialization» or initialization in Spanish. INI files are configuration documents that are widely used in the computing world to store settings and configuration options for programs and applications.

What do INI Files contain?

INI files contain key information that allows programs and applications to function properly. These files can include a wide variety of data, such as:

  • Settings: The values ​​that determine how a program behaves.
  • Paths: Information about the location of files or resources necessary for the operation of the program.
  • User Preferences: Custom settings chosen by the user.
  • Interface options: Details about the design and appearance of the user interface.

How are INI Files Structured?

INI files have a simple but effective structure. They are usually divided into sections, each with its own set of values ​​and settings. Let's look at a basic example:

[Sección 1]
Clave1=Valor1
Clave2=Valor2

[Sección 2]
Clave3=Valor3

In this example, we have two sections, each with its own keys and values. This structure makes it easier to organize and find information in the file.

INI files in action

Now that we have a basic understanding of what INI Files are, it’s time to explore how they are used in the real world and how they can benefit you.

software configuration

One of the most common uses of INI files is software configuration. Many programs use these files to store user preferences. Have you ever customized a program's options and wondered where they are stored? The answer is usually an INI file!

game customization

If you are a gaming enthusiast, you have probably come across INI files. These files are used to adjust game settings, from graphics quality to control settings. You can customize your gaming experience by modifying these files.

Task automation

INI files are also useful in automating tasks. Programs can read and modify these files to perform specific actions on a scheduled basis. This is especially useful in business and system administration environments.

INI files on the web

INI files are not limited to desktop applications. On the web, they are used in technologies like PHP to store configuration information. If you work in web development, understanding how these files work can be essential.

How to use INI Files?

Now that you know what INI Files are and where they are used, it's time to learn how you can use them to your advantage.

1. Identify the relevant INI file

The first thing you need to do is locate the INI file of the program or application you want to configure. It is usually located in the software installation directory.

  What is the digital euro and how will it change our money?

2. Make backups

Before making any changes to an INI file, be sure to make a backup of the original file. This will allow you to restore the previous settings if something goes wrong.

3. Open the INI file

Use a simple text editor, such as Notepad in Windows, to open the INI file. Make sure the editor does not introduce any additional formatting, such as bold or italics.

4. Edit carefully

Make any necessary changes to the file, paying attention to the syntax. INI files are case sensitive, so you must be precise.

5. Save the changes

After making your adjustments, save the INI file and close it. Make sure the software in question is closed before doing so.

6. Test the program

Launch the program and check if the changes have taken effect. If everything works as expected, you have successfully set up an INI file!

Additional tips

Here are some additional tips to get the most out of INI Files:

  • Documentation: Always consult the program or application documentation to better understand the options available in the INI file.
  • Comments: You can add comments to an INI file by preceding the lines with the semicolon symbol (;). This will help you remember the purpose of each setting.
  • Experience: Don't be afraid to experiment with the settings in an INI file. You can learn a lot by trying out different values ​​and seeing how they affect the program.

Examples of reading and writing to INI files

The following examples make use of a common INI file (config.ini), which is shown below:

[BaseDatos]
Usuario=minombre
Password=unaClave

[Preferencias]
Fondo=Blanco
Color=Azul

1) Example in Free Pascal

Below is the complete code to read and write an INI file using Free Pascal

program fileIni;

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes
  { you can add units after this }
  , Sysutils, IniFiles;

const
  ARCHIVO_CONFIG = 'config.ini';

var
  Ini: TIniFile;
  Valor: String;

begin
  { El método Create es el constructor de la clase, que recibe como parámetro
      el nombre del archivo INI.}
  Ini := TIniFile.Create(ARCHIVO_CONFIG);

  {Para leer valores se especifica el nombre de sección y clave
    en los métodos ReadString.}
  // Leer valor de sección BaseDatos
  Valor := Ini.ReadString('BaseDatos','Usuario','');
  WriteLn('Usuario BD: ', Valor);

  // Leer valor de sección Preferencias
  Valor := Ini.ReadString('Preferencias','Fondo', '');
  WriteLn('Color de fondo', Valor);

  {Para escribir valores se indica sección y clave con WriteString
    antes de guardar con UpdateFile.}
  // Escribir valor en sección BaseDatos
  Ini.WriteString('BaseDatos','Password','NuevaClave');

  // Escribir valor en sección Preferencias
  Ini.WriteString('Preferencias', 'Color', 'Verde');

  Ini.UpdateFile;
  Ini.Free;
end.

This code is a program written in Pascal that works with INI files for configuration. Here is a brief explanation of what it does:

  1. Includes the necessary units: The program uses the units Classes, SysUtils, and IniFiles, which provide the functions necessary to work with INI files and other resources.
  2. Defines a constant ARCHIVO_CONFIG which contains the name of the INI file to be used, in this case, "config.ini".
  3. Declare a variable Ini type TIniFile. This variable is used to interact with the INI file.
  4. The program starts by creating an instance of TIniFile call Ini with the builder Create, passing the name of the INI file ("config.ini") as a parameter.
  5. Then use the method ReadString de Ini to read values ​​from the INI file. In this case, two values ​​are read: the first from the “Database” section and “User” key, and the second from the “Preferences” section and “Background” key. The read values ​​are stored in the variable Valor and are displayed in the console.
  6. Then use the method WriteString de Ini to write values ​​to the INI file. In this case, a new password is set in the “Database” section and “Password” key, and the color in the “Preferences” section and “Color” key is changed to “Green”.
  7. Then the method is called UpdateFile to save changes made to the INI file to disk.
  8. Finally, the instance memory is freed. Ini calling to Ini.Free.

In short, this program is used to read and write configuration values ​​in an INI file called “config.ini” in specific sections, and then saves the changes made to the file.

  Easy Step-by-Step Laptop Keyboard Cleaning

2) Example in PHP

Below is the complete code to read and write to an INI file using PHP. It includes the class and usage example in the same script, but you can separate them to follow programming best practices:

<?php

class ManejadorIni
{
    private $filename;
    private $contenido;

    public function __construct($filename)
    {
        if (!file_exists($filename)) {
            throw new Exception('El archivo no existe.');
        }

        $this->filename = $filename;
        $this->contenido = parse_ini_file($filename, true);

        if ($this->contenido === false) {
            throw new Exception('No se pudo analizar el archivo INI.');
        }
    }

    public function leer($seccion, $clave)
    {
        if (isset($this->contenido[$seccion]) && isset($this->contenido[$seccion][$clave])) {
            return $this->contenido[$seccion][$clave];
        }
        return '';
    }

    public function escribir($seccion, $clave, $valor)
    {
        $this->contenido[$seccion][$clave] = $valor;
    }

    public function guardar()
    {
        $texto = "; Archivo INI generado por ManejadorIni\n";
        
        foreach ($this->contenido as $sec => $cont) {
            $texto .= "\n[$sec]\n";
            
            foreach ($cont as $key => $val) {
                $texto .= "$key=$val\n";
            }
        }

        if (file_put_contents($this->filename, $texto) === false) {
            throw new Exception('No se pudo guardar el archivo INI.');
        }
    }

    public function __destruct()
    {
        $this->filename = null;
        $this->contenido = null;
    }
} // Aqui termina la Clase.


// Código para probar la Clase: ManejadorIni
try {
    // Iniciar el manejador para un archivo INI específico
    $manejador = new ManejadorIni('config.ini');

    // Leer valores
    $nombreUsuario = $manejador->leer('BaseDeDatos', 'usuario');
    if (empty($nombreUsuario)) {
        echo "No se pudo obtener el nombre de usuario desde el archivo INI.\n";
    }
    echo "Nombre de Usuario actual: " . $nombreUsuario . "<br>";

    // Escribir valores
    $manejador->escribir('BaseDeDatos', 'usuario', 'nuevoUsuario');

    // Guardar cambios al archivo
    $manejador->guardar();

} catch (Exception $e) {
    // Manejo de excepciones
    echo "Se ha encontrado un error: " . $e->getMessage();
}


?>

This PHP code defines a class called ManejadorIni which is used to read, modify and save configuration files in INI format. Here is the basic functionality of the code:

  1. Class ManejadorIni has private property $filename (to store the INI file name) and $contenido (to store the parsed contents of the INI file).
  2. In the class constructor ManejadorIni, the specified INI file is checked to see if it exists. If it does not exist, an exception is thrown. The constructor then parses the contents of the INI file using the parse_ini_file and stores the result in the property $contenidoIf the parsing function fails, an exception is also thrown.
  3. The class provides three main methods:
    • leer($seccion, $clave): Allows you to read a specific value from a section and key in the INI file. If the section and key exist, it returns the value; otherwise, it returns an empty string.
    • escribir($seccion, $clave, $valor): Allows you to write or modify a value in the INI file for a given section and key. This modification is done in memory, and is not saved to the file until the method is called. guardar().
    • guardar(): Saves the changes made in memory to the original INI file. Goes through the contents stored in $this->contenido and writes it back to the INI file.
  4. The method __destruct() It is responsible for cleaning up the properties when the class instance is destroyed.
  5. Outside the class definition, an example of usage is given:
    • An instance is created ManejadorIni for the 'config.ini' file.
    • The value of the 'user' key is read from the 'Database' section of the INI file.
    • If the value is empty, an error message is displayed.
    • The value of 'user' is changed to 'newUser'.
    • Changes are saved to the INI file.
  Types of Measurement Errors: An Introductory Guide

The code also handles exceptions, so if errors occur while reading, writing, or saving the INI file, they are caught and an appropriate error message is displayed instead of causing the program to abort.

NOTE: The PHP script does not make use of advanced PHP 7.x syntax as it attempts to be compatible with PHP 5.6 and PHP 7.

3) Example in Python

Below we show the functionality of reading and writing to the INI file: config.ini using Python:

import configparser

# Crear un objeto ConfigParser
config = configparser.ConfigParser()

# Leer el archivo INI
config.read('config.ini')

# Leer valores del archivo INI
usuario_bd = config.get('BaseDatos', 'Usuario')
password_bd = config.get('BaseDatos', 'Password')
fondo = config.get('Preferencias', 'Fondo')
color = config.get('Preferencias', 'Color')

# Mostrar los valores leídos
print('Usuario BD:', usuario_bd)
print('Password BD:', password_bd)
print('Fondo:', fondo)
print('Color:', color)

# Escribir valores en el archivo INI
config.set('BaseDatos', 'Usuario', 'nuevo_usuario')
config.set('BaseDatos', 'Password', 'NuevaClave2')
config.set('Preferencias', 'Fondo', 'Red')
config.set('Preferencias', 'Color', 'Azul')

# Guardar los cambios en el archivo INI
with open('config.ini', 'w') as configfile:
    config.write(configfile)

The Python program uses the library configparser to read and write to an INI file called “config.ini”. Here is a brief explanation of what it does:

  1. Import the library configparser to work with INI files.
  2. Create an object ConfigParser called config.
  3. Read the INI file using the method read de config.
  4. Reads the existing values ​​in the INI file for the "Database" and "Preferences" sections using the method get. Then, display these values ​​to the console.
  5. Updates the values ​​in the INI file using the method setIn this case, change the username and password in the “Database” section, and the background and color in the “Preferences” section.
  6. Save changes to the INI file using the method write and an output file called “config.ini”.

In short, the program allows you to read, modify and save values ​​in an INI file using the library configparser Python.

Conclusion

INI Files may seem like a mystery at first, but with the right information and some practice, you'll become an expert at using them. These simple configuration documents play a crucial role in customizing software, optimizing games, and automating tasks. So don't be afraid to delve into the world of INI Files and start harnessing their potential today!

It should be remembered that there are also other types of configuration files called XML, which are used in different areas of computing such as databases, information exchange or application configuration. XML is an extensible markup language that allows structuring and storing data in a format readable by both humans and machines. Unlike the traditional configuration file based on plain text, the XML format uses tags and attributes to define the structure of the document.

If you found this guide on INI Files useful, feel free to share it with other computer and technology enthusiasts. Together, we can simplify the INI Files puzzle and make them accessible to everyone. Share the knowledge and help others master this powerful configuration tool!