The physical mechanism responsible for coronal mass ejections has been uncertain for many years, in large part because of the difficulty of knowing the three-dimensional magnetic field in the low corona1. Two possible models have emerged. In the first, a twisted flux rope moves out of equilibrium or becomes unstable, and the subsequent reconnection then powers the ejection2, 3, 4, 5. In the second, a new flux rope forms as a result of the reconnection of the magnetic lines of an arcade (a group of arches of field lines) during the eruption itself6. Observational support for both mechanisms has been claimed7, 8, 9. Here we report modelling which demonstrates that twisted flux ropes lead to the ejection, in support of the first model. After seeing a coronal mass ejection, we use the observed photospheric magnetic field in that region from four days earlier as a boundary condition to determine the magnetic field configuration. The field evolves slowly before the eruption, such that it can be treated effectively as a static solution. We find that on the fourth day a flux rope forms and grows (increasing its free energy). This solution then becomes the initial condition as we let the model evolve dynamically under conditions driven by photospheric changes (such as flux cancellation). When the magnetic energy stored in the configuration is too high, no equilibrium is possible and the flux rope is ‘squeezed’ upwards. The subsequent reconnection drives a mass ejection.