Import Multiple Python libraries

Annoyed writing multiple import statements? how to import a list of libraries from a txt file?

GeoSense ✅
2 min readMar 13, 2023

--

Yes, you can import a list of libraries from a txt file in Python. It is very simple.

Example: we have a text file libraries.txt as below:

import numpy as np
import matplotlib.pyplot as plt
import rasterio

If your text file contains the import statements you’ve listed above, you can use the exec function in Python to execute these statements in your code.

Here is some sample code that demonstrates how to import a list of libraries from a txt file containing import statements:

with open('libraries.txt', 'r') as f:
lines = f.readlines()

for line in lines:
exec(line)

In this code, we first open the libraries.txt file in read mode and read each line into a list called lines. Each line in the file represents an import statement.

We then use a for loop to iterate over each line in the lines list and use the exec function to execute the statement. The exec function allows you to execute arbitrary Python code in your program.

Note that using the exec function to execute arbitrary code can be potentially dangerous, so you should ensure that the contents of the libraries.txt file are trustworthy before running this code. Additionally, you should avoid using exec with untrusted user input as it can lead to security vulnerabilities.

Import multiple Python libraries

Thank You for Reading!

--

--

GeoSense ✅

🌏 Remote sensing | 🛰️ Geographic Information Systems (GIS) | ℹ️ https://www.tnmthai.com/medium