Question: How to convert the string to a CSV file in Python?
The desired output is the CSV file:
'my_file.csv':
a,b,c
1,2,3
9,8,7
Simple Vanilla Python Solution
To convert a multi-line string with comma-separated values to a CSV file in Python, simply write the string in a file (e.g., with the name 'my_file.csv') without further modification.
This works if the string is already in the correct CSV format with values separated by commas.
The following code uses the open() function and the file.write() functions to write the multi-line string to a file without modification.
my_string = '''a,b,c
1,2,3
9,8,7''' with open('my_file.csv', 'w') as out: out.write(my_string)
The result is a file 'my_file.csv' with the following contents:
a,b,c
1,2,3
9,8,7
Parsing and Modifying Text to CSV
The string may not be in the correct CSV format.
For example, you may want to convert any of the following strings to a CSV file—their format is not yet ready for writing it directly in a comma-separated file (CSV):
Example 1: 'abc;123;987'
Example 2: 'abc 123 987'
Example 3: 'a=b=c 1=2=3 9=8=7'
…
To parse such a string and modify it before writing it in a file 'my_file.csv', you can use the string.replace() and string.split() methods to make sure that each value is separated by a comma and each row has its own line.
Let’s go over each of those examples to see how to parse the string effectively to bring it into the CSV format:
Example 1
# Example 1:
my_string = 'abc;123;987' with open('my_file.csv', 'w') as out: lines = [','.join(line) for line in my_string.split(';')] my_string = '\n'.join(lines) out.write(my_string)
I’ve higlighted the two code lines that convert the string to the CSV format.
The first highlighted line uses list comprehension to create a list of three lines, each interleaved with a comma.
The second highlighted line uses the string.join() function to bring those together to a CSV format that can be written into the output file.
The output file 'my_file.csv' contains the same CSV formatted text:
a,b,c
1,2,3
9,8,7
Example 2
The following example is the same as the previous code snippet, only that the empty spaces ' ' in the input string should be converted to new lines to obtain the final CSV:
# Example 2:
my_string = 'abc 123 987' with open('my_file.csv', 'w') as out: lines = [','.join(line) for line in my_string.split(' ')] my_string = '\n'.join(lines) out.write(my_string)
The output file 'my_file.csv' contains the same CSV formatted text:
a,b,c
1,2,3
9,8,7
Example 3
If the comma-separated values are not yet comma-separated (e.g., they may be semicolon-separated 'a;b;c'), you can use the string.replace() method to replace the symbols accordingly.
This is shown in the following example:
# Example 3:
my_string = 'a=b=c 1=2=3 9=8=7' with open('my_file.csv', 'w') as out: my_string = my_string.replace('=', ',').replace(' ', '\n') out.write(my_string)
Thanks for reading this article! I appreciate the time you took to learn Python with me.
If you’re interested in writing more concise code, feel free to check out my one-liner book here:
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Abstract: In this article, we’ll quickly overview the best method, respectively, to convert a CSV file to JSON, Excel, dictionary, Parquet, list, list of lists, list of tuples, text file, DataFrame, XML, NumPy array, and list of dictionaries.
In this article, you’ve learned the best ways to perform the following conversions (click to read more):
You can convert a CSV file to a JSON file by using the following five steps:
Import the csv and json libraries
Open the CSV as a file object in reading mode using the open(path_to_csv, 'r') function in a context manager (=with environment).
Load the CSV content into Python using the csv.DictReader(fobj) and pass the file object just created.
Iterate over each row and update a newly-created dictionarymy_json using one of the column values as key: my_json[key] = row
Store the my_json dictionary data in a JSON file using the json.dumps(my_json) function.
import csv
import json csv_file = 'my_file.csv'
json_file = 'my_file.json' my_json = {}
with open(csv_file, 'r') as fobj: reader = csv.DictReader(fobj) for row in reader: # Use one of the CSV column names as a key key = row['Name'] my_json[key] = row with open(json_file,'w') as fobj: fobj.write(json.dumps(my_json, indent=2))
There are many more details to it, so if this didn’t answer your question yet, go here:
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert CSV to Excel (XLSX) in Python?
The most pythonic way to convert a .csv to an .xlsx (Excel) in Python is to use the Pandas library.
Store the DataFrame in an Excel file by calling df.to_excel('my_file.xlsx', index=None, header=True)
import pandas as pd df = pd.read_csv('my_file.csv')
df.to_excel('my_file.xlsx', index=None, header=True)
Note that there are many ways to customize the to_excel() function in case
you donβt need a header line,
you want to fix the first line in the Excel file,
you want to format the cells as numbers instead of strings, or
you have an index column in the original CSV and want to consider it in the Excel file too.
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a Dictionary in Python?
The best way to convert a CSV file to a Python dictionary is to create a CSV file object f using open("my_file.csv") and pass it in the csv.DictReader(f) method. The return value is an iterable of dictionaries, one per row in the CSV file, that maps the column header from the first row to the specific row value.
import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.DictReader(f) for row in reader: print(row)
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a Parquet Format in Python?
Hereβs a step-by-step approach to reading a CSV and converting its contents to a Parquet file using the Pandas library:
Step 1: Run pip install pandas if the module is not already installed in your environment.
Step 3: Run pip install fastparquet to install the fastparquet module
Step 4: import pandas using import pandas as pd
Step 5: Read the CSV file into a DataFrame using df = pd.read_csv('my_file.csv').
Step 6: Write the Parquet file using df.to_parquet('my_file.parquet')
The code snippet to convert a CSV file to a Parquet file is quite simple (steps 4-6):
import pandas as pd
df = pd.read_csv('my_file.csv')
df.to_parquet('my_file.parquet')
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a List in Python?
Hereβs the code to convert that CSV file to a list of dictionaries, one dictionary per row by using the csv.DictReader(file) function:
import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.DictReader(f) lst = list(*reader)
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a List of Lists in Python?
To convert a CSV file 'my_file.csv' into a list of lists in Python, use the csv.reader(file_obj) method to create a CSV file reader. Then convert the resulting object to a list using the list() constructor.
import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.reader(f) lst = list(reader)
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a List of Tuples in Python?
To convert a CSV file 'my_file.csv' into a list of tuples in Python, use csv.reader(file_obj) to create a CSV file reader that holds an iterable of lists, one per row. Now, use the list(tuple(line) for line in reader) expression with a generator expression to convert each inner list to a tuple.
Hereβs a simple example that converts our CSV file to a list of tuples using this approach:
import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.reader(f) lst = list(tuple(line) for line in reader)
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a Text File in Python?
If you want to keep the content (including the delimiter ',') in the CSV file unmodified, the conversion is simple: read the .csv file and write its content into a new .txt file using the open(), read(), and write() functions without importing any library.
In other words, perform the three steps to write a CSV to a TXT file unmodified:
Open the CSV file in reading mode and the TXT file in writing mode.
Read the CSV file and store it in a variable.
Write the content into the TXT file.
Hereβs the code snippet that solves our basic challenge:
# 1. Open the CSV file in reading mode and the TXT file in writing mode
with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out: # 2. Read the CSV file and store in variable content = f_in.read() # 3. Write the content into the TXT file f_out.write(content)
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a Pandas DataFrame in Python?
To import a given CSV file into a newly-created Pandas DataFrame, use the pd.read_csv('my_file.csv') function that returns a DataFrame created with the content in the CSV file 'my_file.csv'.
Hereβs a quick and generic code snippet showcasing this approach:
import pandas as pd
df = pd.read_csv('my_file.csv')
print(df)
Output:
Name Job Age Income
0 Alice Programmer 23 110000
1 Bob Executive 34 90000
2 Carl Sales 45 50000
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to an XML in Python?
You can convert a CSV to an XML using the following approach:
Read the whole CSV file into your Python script.
Store the first row as header data that is needed to name your custom XML tags (e.g., <Name>, <Job>, <Age>, and <Income> in our example).
Create a function convert_row() that converts each row separately to an XML representation of that row using basic string formatting.
Iterate over the data row-wise using csv.reader() and convert each CSV row to XML using your function convert_row().
Here’s the code:
# Convert CSV file to XML string
import csv filename = 'my_file.csv' def convert_row(headers, row): s = f'<row id="{row[0]}">\n' for header, item in zip(headers, row): s += f' <{header}>' + f'{item}' + f'</{header}>\n' return s + '</row>' with open(filename, 'r') as f: r = csv.reader(f) headers = next(r) xml = '<data>\n' for row in r: xml += convert_row(headers, row) + '\n' xml += '</data>' print(xml)
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a NumPy Array in Python?
You can convert a CSV file to a NumPy array simply by calling np.loadtxt() with two arguments: the filename and the delimiter string. For example, the expression np.loadtxt('my_file.csv', delimiter=',') returns a NumPy array from the 'my_file.csv' with delimiter symbols ','.
Here’s an example:
import numpy as np array = np.loadtxt('my_file.csv', delimiter=',')
print(array)
Output:
[[9. 8. 7.] [6. 5. 4.] [3. 2. 1.]]
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
How to Convert a CSV to a List of Dictionaries?
Convert a CSV file to a list of Python dictionaries in three steps:
Create a CSV file object f using open("my_file.csv") and pass it in the csv.DictReader(f) method.
The return value is an iterable of dictionaries, one per row in the CSV file. Each dictionary maps the column header from the first row to the specific row value.
As the last step, convert the iterable of dictionaries to a list using the Python built-in list() function.
Hereβs the code to convert that CSV file to a list of dictionaries, one dictionary per row by using the csv.DictReader(file) function:
import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.DictReader(f) lst = list(*reader)
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.
Summary
You can find a more detailed article on each topic in the following table:
If you’re short on time, the simple solution is to run the following command in your shell/terminal/CMD/PowerShell to check the version of library xxx:
pip show xxx
But many more interesting ways to check package versions may be useful for you!
The following table refers to a list of articles to help you check the package/library/module version installed in your environment. You can use the STRG+F search hotkey to find the relevant package name you want to check the package version for.
This article will show you how to use the BeforeAfter image component in your Plotly Dash project.
Dash book author Ann just created the following stunning web project visualizing before/after galaxy images from the James Webb Space Telescope in a simple and straightforward Dash app using the BeforeAfter component of the dash-extensions library.
pip install dash-extensions
Before we dive into the code, here’s a screenshot of the stunning interactive dashboard visualization created in the project:
Feel free to visit the live app showing different exciting images from the Hubble and Webb telescopes here:
Adam’s video greatly explains the Before After Image Slider — feel free to watch it and leave a like in the video for his effort educating the Dash community for free with outstanding content:
You can find a tutorial on how to install dash here.
In this article, you’ll learn how to increment a dictionary value in Python.
To make it more fun, we have the following running scenario:
Trinity Bank keeps track of its latest mortgage rates in a Dictionary format. Recently there has been a steady increase in rates. How would Trinity Bank increment/increase the Dictionary value of a selected rate?
In this example, the 20 Year Fixed mortgage rate is referenced and accessed using (mtg_rates.get('20-Year-Fixed')). This value is then incremented by two (2).
Then, this updated value is saved back to mtg_rates['20-Year-Fixed'] and output to the terminal.
7.25
Method 3: Use Dictionary.update()
This method uses Dictionary.update() to reference the appropriate Key and increment the Value.
new_rates = dict(((key, round(value*1.10, 3)) for key, value in mtg_rates.items()))
print(new_rates)
Above, accesses each mortgage rate in the mtg_rates Dictionary and increments the rate by 1.10. Then, round() is called to round the results down to three (3) decimal places. The result saves to new_rates and output to the terminal.
How to check the version of the Python module (package, library) future? And how to check if future is installed anyways?
These are the eight best ways to check the installed version of the Python module future:
Method 1: pip show future
Method 2: pip list
Method 3: pip list | findstr future
Method 4: library.__version__
Method 5: importlib.metadata.version
Method 6: conda list
Method 7: pip freeze
Method 8: pip freeze | grep future
Before we go into these ways to check your future version, let’s first quickly understand how versioning works in Python—you’ll be thankful to have spent a few seconds on this topic, believe me!
A Note on Python Version Numbering
Python versioning adds a unique identifier to different package versions using semantic versioning. Semantic versioning consists of three numerical units of versioning information in the format major.minor.patch.
In this tutorial, we’ll use the shorthand general version abbreviation like so:
x.y.z
Practical examples would use numerical values for x, y, and z:
1.2.3
4.1.4
1.0.0
This is shorthand for
major.minor.patch
Major releases (0.1.0 to 1.0.0) are used for the first stable release or “breaking changes”, i.e., major updates that break backward compatibility.
Minor releases (0.1.0 to 0.2.0) are used for larger bug fixes and new features that are backward compatible.
Patch releases (0.1.0 to 0.1.1) are used for smaller bug fixes that are backward compatible.
Let’s dive into the meat of this article:
Question: How to check the (major, minor, patch) version of future in your current Python environment?
Method 1: pip show
To check which version of the Python library future is installed, run pip show future or pip3 show future in your CMD/Powershell (Windows), or terminal (macOS/Linux/Ubuntu).
This will work if your pip installation is version 1.3 or higher—which is likely to hold in your case because pip 1.3 was released a decade ago in 2013!!
Here’s an example in my Windows Powershell: I’ve highlighted the line that shows that my package version is a.b.c:
In some instances, this will not work—depending on your environment. In this case, try those commands before giving up:
python -m pip show future
python3 -m pip show future
py -m pip show future
pip3 show future
Next, we’ll dive into more ways to check your future version.
But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
To check the versions of all installed packages, use pip list and locate the version of future in the output list of package versions sorted alphabetically.
This will work if your pip installation is version 1.3 or higher.
Here’s a simplified example for Windows Powershell, I’ve highlighted the line that shows the package version is 1.2.3:
PS C:\Users\xcent> pip list
Package Version
--------------- ---------
aaa 1.2.3
...
future 1.2.3
...
zzz 1.2.3
In some instances, this will not work—depending on your environment. Then try those commands before giving up:
python -m pip list
python3 -m pip list
py -m pip list
pip3 list
Method 3: pip list + findstr on Windows
To check the versions of a single package on Windows, you can chain pip list with findstr future using the CMD or Powershell command: pip3 list | findstr future to locate the version of future in the output list of package versions automatically.
Here’s an example for future:
pip3 list | findstr future 1.2.3
Method 4: Module __version__ Attribute
To check which version is installed of a given library, you can use the library.__version__ attribute after importing the library (package, module) with import library.
Here’s the code:
import my_library
print(my_library.__version__)
# x.y.z for your version output
Here’s an excerpt from the PEP 8 docs mentioning the __version__ attribute.
“PEP 8 describes the use of a module attribute called __version__ for recording “Subversion, CVS, or RCS” version strings using keyword expansion. In the PEP authorβs own email archives, the earliest example of the use of an __version__ module attribute by independent module developers dates back to 1995.”
You can also use the following one-liner snippet to run this from your terminal (macOS, Linux, Ubuntu) or CMD/Powershell (Windows):
However, this method doesn’t work for all libraries, so while simple, I don’t recommend it as a general approach for that reason.
Method 5: importlib.metadata.version
The importlib.metadata library provides a general way to check the package version in your Python script via importlib.metadata.version('future') for library future. This returns a string representation of the specific version such as 1.2.3 depending on the concrete version in your environment.
If you have created your Python environment with Anaconda, you can use conda list to list all packages installed in your (virtual) environment. Optionally, you can add a regular expression using the syntax conda list regex to list only packages matching a certain pattern.
How to list all packages in the current environment?
conda list
How to list all packages installed into the environment 'xyz'?
conda list -n xyz
Regex: How to list all packages starting with 'future'?
conda list '^future'
Method 7: pip freeze
The pip freeze command without any option lists all installed Python packages in your environment in alphabetically order (ignoring UPPERCASE or lowercase). You can spot your specific package future if it is installed in the environment.
pip freeze
Output example (depending on your concrete environment/installation):
To check the versions of a single package on Linux/Ubuntu/macOS, you can chain pip freeze with grep future using the CMD or Powershell command: pip freeze | grep future to programmatically locate the version of your particular package future in the output list of package versions.
Here’s an example for future:
pip freeze | grep future
future==1.2.3
Related Questions
Check future Installed Python
How to check if future is installed in your Python script?
To check if future is installed in your Python script, you can run import future in your Python shell and surround it by a try/except to catch a potential ModuleNotFoundError.
How to check the package version of future in Python?
To check which version of future is installed, use pip show future or pip3 show future in your CMD/Powershell (Windows), or terminal (macOS/Linux/Ubuntu) to obtain the output major.minor.patch.
pip show future # or pip3 show future
# 1.2.3
Check future Version Linux
How to check my future version in Linux?
To check which version of future is installed, use pip show future or pip3 show future in your Linux terminal.
pip show future # or pip3 show future
# 1.2.3
Check future Version Ubuntu
How to check my future version in Ubuntu?
To check which version of future is installed, use pip show future or pip3 show future in your Ubuntu terminal.
pip show future # or pip3 show future
# 1.2.3
Check future Version Windows
How to check my future version on Windows?
To check which version of future is installed, use pip show future or pip3 show future in your Windows CMD, command line, or PowerShell.
pip show future # or pip3 show future
# 1.2.3
Check future Version Mac
How to check my future version on macOS?
To check which version of future is installed, use pip show future or pip3 show future in your macOS terminal.
pip show future # or pip3 show future
# 1.2.3
Check future Version Jupyter Notebook
How to check my future version in my Jupyter Notebook?
To check which version of future is installed, add the line !pip show future to your notebook cell where you want to check. Notice the exclamation mark prefix ! that allows you to run commands in your Python script cell.
!pip show future
Output: The following is an example on how this looks for future in a Jupyter Notebook cell:
How to check the future version in my conda installation?
Use conda list 'future' to list version information about the specific package installed in your (virtual) environment.
conda list 'future'
Check future Version with PIP
How to check the future version with pip?
You can use multiple commands to check the future version with PIP such as pip show future, pip list, pip freeze, and pip list.
pip show future
pip list
pip freeze
pip list
The former will output the specific version of future. The remaining will output the version information of all installed packages and you have to locate future first.
Check Package Version in VSCode or PyCharm
How to check the future version in VSCode or PyCharm?
Integrated Development Environments (IDEs) such as VSCode or PyCharm provide a built-in terminal where you can run pip show future to check the current version of future in the specific environment you’re running the command in.
pip show future
pip3 show future pip list
pip3 list pip freeze
pip3 freeze
You can type any of those commands in your IDE terminal like so:
Summary
In this article, you’ve learned those best ways to check a Python package version:
Method 1: pip show future
Method 2: pip list
Method 3: pip list | findstr future
Method 4: library.__version__
Method 5: importlib.metadata.version
Method 6: conda list
Method 7: pip freeze
Method 8: pip freeze | grep future
Thanks for giving us your valued attention — we’re grateful to have you here!
Programmer Humor
There are only 10 kinds of people in this world: those who know binary and those who donβt. ~~~
There are 10 types of people in the world. Those who understand trinary, those who donβt, and those who mistake it for binary.
These are the eight best ways to check the installed version of the Python module abc:
Method 1: pip show abc
Method 2: pip list
Method 3: pip list | findstr abc
Method 4: library.__version__
Method 5: importlib.metadata.version
Method 6: conda list
Method 7: pip freeze
Method 8: pip freeze | grep abc
Before we go into these ways to check your abc version, let’s first quickly understand how versioning works in Python—you’ll be thankful to have spent a few seconds on this topic, believe me!
A Note on Python Version Numbering
Python versioning adds a unique identifier to different package versions using semantic versioning. Semantic versioning consists of three numerical units of versioning information in the format major.minor.patch.
In this tutorial, we’ll use the shorthand general version abbreviation like so:
x.y.z
Practical examples would use numerical values for x, y, and z:
1.2.3
4.1.4
1.0.0
This is shorthand for
major.minor.patch
Major releases (0.1.0 to 1.0.0) are used for the first stable release or “breaking changes”, i.e., major updates that break backward compatibility.
Minor releases (0.1.0 to 0.2.0) are used for larger bug fixes and new features that are backward compatible.
Patch releases (0.1.0 to 0.1.1) are used for smaller bug fixes that are backward compatible.
Let’s dive into the meat of this article:
Question: How to check the (major, minor, patch) version of abc in your current Python environment?
Method 1: pip show
To check which version of the Python library abc is installed, run pip show abc or pip3 show abc in your CMD/Powershell (Windows), or terminal (macOS/Linux/Ubuntu).
This will work if your pip installation is version 1.3 or higher—which is likely to hold in your case because pip 1.3 was released a decade ago in 2013!!
Here’s an example in my Windows Powershell: I’ve highlighted the line that shows that my package version is a.b.c:
In some instances, this will not work—depending on your environment. In this case, try those commands before giving up:
python -m pip show abc
python3 -m pip show abc
py -m pip show abc
pip3 show abc
Next, we’ll dive into more ways to check your abc version.
But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
To check the versions of all installed packages, use pip list and locate the version of abc in the output list of package versions sorted alphabetically.
This will work if your pip installation is version 1.3 or higher.
Here’s a simplified example for Windows Powershell, I’ve highlighted the line that shows the package version is 1.2.3:
PS C:\Users\xcent> pip list
Package Version
--------------- ---------
aaa 1.2.3
...
abc 1.2.3
...
zzz 1.2.3
In some instances, this will not work—depending on your environment. Then try those commands before giving up:
python -m pip list
python3 -m pip list
py -m pip list
pip3 list
Method 3: pip list + findstr on Windows
To check the versions of a single package on Windows, you can chain pip list with findstr abc using the CMD or Powershell command: pip3 list | findstr abc to locate the version of abc in the output list of package versions automatically.
Here’s an example for abc:
pip3 list | findstr abc 1.2.3
Method 4: Module __version__ Attribute
To check which version is installed of a given library, you can use the library.__version__ attribute after importing the library (package, module) with import library.
Here’s the code:
import my_library
print(my_library.__version__)
# x.y.z for your version output
Here’s an excerpt from the PEP 8 docs mentioning the __version__ attribute.
“PEP 8 describes the use of a module attribute called __version__ for recording “Subversion, CVS, or RCS” version strings using keyword expansion. In the PEP authorβs own email archives, the earliest example of the use of an __version__ module attribute by independent module developers dates back to 1995.”
You can also use the following one-liner snippet to run this from your terminal (macOS, Linux, Ubuntu) or CMD/Powershell (Windows):
However, this method doesn’t work for all libraries, so while simple, I don’t recommend it as a general approach for that reason.
Method 5: importlib.metadata.version
The importlib.metadata library provides a general way to check the package version in your Python script via importlib.metadata.version('abc') for library abc. This returns a string representation of the specific version such as 1.2.3 depending on the concrete version in your environment.
If you have created your Python environment with Anaconda, you can use conda list to list all packages installed in your (virtual) environment. Optionally, you can add a regular expression using the syntax conda list regex to list only packages matching a certain pattern.
How to list all packages in the current environment?
conda list
How to list all packages installed into the environment 'xyz'?
conda list -n xyz
Regex: How to list all packages starting with 'abc'?
conda list '^abc'
Method 7: pip freeze
The pip freeze command without any option lists all installed Python packages in your environment in alphabetically order (ignoring UPPERCASE or lowercase). You can spot your specific package abc if it is installed in the environment.
pip freeze
Output example (depending on your concrete environment/installation):
To check the versions of a single package on Linux/Ubuntu/macOS, you can chain pip freeze with grep abc using the CMD or Powershell command: pip freeze | grep abc to programmatically locate the version of your particular package abc in the output list of package versions.
Here’s an example for abc:
pip freeze | grep abc
abc==1.2.3
Related Questions
Check abc Installed Python
How to check if abc is installed in your Python script?
To check if abc is installed in your Python script, you can run import abc in your Python shell and surround it by a try/except to catch a potential ModuleNotFoundError.
How to check the package version of abc in Python?
To check which version of abc is installed, use pip show abc or pip3 show abc in your CMD/Powershell (Windows), or terminal (macOS/Linux/Ubuntu) to obtain the output major.minor.patch.
pip show abc # or pip3 show abc
# 1.2.3
Check abc Version Linux
How to check my abc version in Linux?
To check which version of abc is installed, use pip show abc or pip3 show abc in your Linux terminal.
pip show abc # or pip3 show abc
# 1.2.3
Check abc Version Ubuntu
How to check my abc version in Ubuntu?
To check which version of abc is installed, use pip show abc or pip3 show abc in your Ubuntu terminal.
pip show abc # or pip3 show abc
# 1.2.3
Check abc Version Windows
How to check my abc version on Windows?
To check which version of abc is installed, use pip show abc or pip3 show abc in your Windows CMD, command line, or PowerShell.
pip show abc # or pip3 show abc
# 1.2.3
Check abc Version Mac
How to check my abc version on macOS?
To check which version of abc is installed, use pip show abc or pip3 show abc in your macOS terminal.
pip show abc # or pip3 show abc
# 1.2.3
Check abc Version Jupyter Notebook
How to check my abc version in my Jupyter Notebook?
To check which version of abc is installed, add the line !pip show abc to your notebook cell where you want to check. Notice the exclamation mark prefix ! that allows you to run commands in your Python script cell.
!pip show abc
Output: The following is an example on how this looks for abc in a Jupyter Notebook cell:
How to check the abc version in my conda installation?
Use conda list 'abc' to list version information about the specific package installed in your (virtual) environment.
conda list 'abc'
Check abc Version with PIP
How to check the abc version with pip?
You can use multiple commands to check the abc version with PIP such as pip show abc, pip list, pip freeze, and pip list.
pip show abc
pip list
pip freeze
pip list
The former will output the specific version of abc. The remaining will output the version information of all installed packages and you have to locate abc first.
Check Package Version in VSCode or PyCharm
How to check the abc version in VSCode or PyCharm?
Integrated Development Environments (IDEs) such as VSCode or PyCharm provide a built-in terminal where you can run pip show abc to check the current version of abc in the specific environment you’re running the command in.
pip show abc
pip3 show abc pip list
pip3 list pip freeze
pip3 freeze
You can type any of those commands in your IDE terminal like so:
Summary
In this article, you’ve learned those best ways to check a Python package version:
Method 1: pip show abc
Method 2: pip list
Method 3: pip list | findstr abc
Method 4: library.__version__
Method 5: importlib.metadata.version
Method 6: conda list
Method 7: pip freeze
Method 8: pip freeze | grep abc
Thanks for giving us your valued attention — we’re grateful to have you here!
Programmer Humor
There are only 10 kinds of people in this world: those who know binary and those who donβt. ~~~
There are 10 types of people in the world. Those who understand trinary, those who donβt, and those who mistake it for binary.
The following career paths for coders interested in the broad database space are ordered alphabetically. The table shows the annual income of different job descriptions in the database space:
Job/Career Description
Annual Income $USD (Lower)
Annual Income $USD (Higher)
Cassandra Developer
110,000
145,000
Couchbase Developer
87,000
212,000
Database Administrator
83,000
131,000
Database Developer
72,000
135,000
DynamoDB Developer
70,000
160,000
IBM DB2 Developer
90,000
132,000
MariaDB Developer
70,000
100,000
Microsoft SQL Server Developer
74,000
137,000
MongoDB Developer
59,000
146,000
MS Access Developer
45,000
75,000
MySQL Developer
87,000
149,000
Oracle Developer
86,000
107,000
PL-SQL Developer
72,000
103,000
PostgreSQL Developer
104,000
133,000
RavenDB Developer
101,000
130,000
Redis Developer
100,000
126,000
SQL Developer
76,000
87,000
SQLite Developer
49,000
107,000
Table: Annual income in the US ($) of different job descriptions in the database space
Let’s dive into each of those job descriptions next!
Cassandra Developer
Cassandra is a free, open-source, distributed, NoSQL database management system (DBMS) for large amounts of data that may be distributed across many commodity servers.
A Cassandra developer manages the Cassandra system and integrates applications with the database storage solution and API.
The average annual income of a Cassandra Developer is between $110,000 and $145,500, according to Glassdoor (source).
Do you want to become a Cassandra Developer? Hereβs a learning path Iβd propose in five steps to get started:
Couchbase is an open-source, distributed NoSQL database infrastructure for interactive applications to serve concurrent users.
A Couchbase developer creates applications using this infrastructureβmostly for business clients.
The average Couchbase salary ranges from approximately $87,504 per year for an Inside Sales Representative to $212,621 per year for a Senior Software Engineer (source).
A database administrator (DBA) is an IT professional responsible for maintaining the reliable, efficient, and secure execution of a database management system (DBMS).
In this way, a database administrator is responsible for providing the data infrastructure of a company or organization. This involves installing, configuring, debugging, optimizing, securing, troubleshooting, and managing database systems.
DBAs can either work as employees or as freelancers remotely or onsite.
Figure: Average Income of a Database Admin in the US by Source. [1]
The average annual income of a Database Administrator in the United States is between $83,533 and $131,056, with an average of $100,920 and a statistical median of $98,860 per year.
A database engineer is responsible for providing the data infrastructure of a company or organization. This involves designing, creating, installing, configuring, debugging, optimizing, securing, and managing databases.
Database engineers can either work as employees or as freelancers remotely or onsite.
A database engineer has the following responsibilities:
Creating a new database system.
Finding a database system tailored to the needs of an organization.
Designing the data models.
Accessing the data with scripting languages including SQL-like syntax.
Installing an existing database software system onsite.
Configuring a database system.
Optimizing a database management system for performance, speed, or reliability.
Consulting management regarding data management issues.
Keeping databases secure and providing proper access control to users.
Monitoring and managing an existing database system to keep it running smoothly.
Debugging potential bugs, errors, and security issues detected at runtime.
Testing and deploying a database system on a public cloud infrastructure such as AWS.
Handling distribution issues in the case of a distributed database management system.
Ensuring budget adherence when running on a public cloud and estimating costs for private database solutions.
Communicating and negotiating with salespeople (e.g., from Oracle).
The average annual income of a Database Engineer in the United States is between $72,536 and $135,000, with an average of $103,652 and a statistical median of $106,589 per year.
Figure: Average Income of a Database Engineer in the US by Source. [1]
Amazonβs DynamoDB is a NoSQL, serverless, key-value database for high-performance applications. It is fully managed so a DynamoDB developer usually helps clients set up and connect to the databaseβand provides minimal maintenance support.
As a DynamoDB Developer, you can expect to earn between $70,000 and $160,000 per year according to Google (source).
Do you want to become a DynamoDB Developer?
Hereβs a learning path Iβd propose in five steps to get started:
Note: If I may be so blunt—I don’t recommend this career path anymore due to the “dying” interest in IBM DB2 technology.
IBM DB2 is a data processing and storage solution that helps developers quickly build and deploy applications such as natural language querying and AI. An IBM DB2 developer creates apps for and integrates them into this system.
The average annual income of an IBM DB2 Developer is $132,000 according to Glassdoor (source).
MariaDB is a database framework focusing on relational databases that are compatible with Oracle. MariaDB developers provide value to clients by integrating their applications with new or existing MariaDB databases. (Source)
The average annual income of a MariaDB Developer is $85,000 according to Payscale (source).
Microsoft SQL Server is a relational database management system (RDBMS) to store and retrieve data on the same computer or across a network. A Microsoft SQL Server Developer creates and connects applications that access the Microsoft SQL Server API. (Source)
The average annual income of a Microsoft SQL Server Developer is between $74,000 and $137,500 according to Ziprecruiter (source):
The average annual income of a MongoDB Developer is $92,414 with a most likely range between $59,000 and $146,000 and a top earner income of $222,000 according to Glassdoor (source).
MongoDB is a source-available cross-platform document-oriented database program. As a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.
A MongoDB developer implements, maintains, and designs MongoDB database applications. (Source)
The average annual income of an MS Access Developer is between $45,000 (25th percentile) and $75,000 (75th percentile) according to Ziprecruiter with top developers making $122,000 and more (source).
A Microsoft Access Developer developer creates, edits, analyzes, debugs, and supervises the development of software written in the MS Access programming language.
MS Access is a database system. Although it isnβt used that much anymore, it is still a great tool for small projects. And there is a huge number of legacy systems that depend upon MS Access. (Source)
A MySQL Developer is responsible for database administration, such as performance optimization, troubleshooting, problem-solving, and customer support.
The average annual income of a MySQL Developer is between $87,828 and $149,975, according to Glassdoor (source).
An Oracle developer creates or maintains the database components of an Oracle application. They often develop new applications or convert existing applications to run in an Oracle Database environment. (Source)
The average annual income of an Oracle Developer in the United States is between $86,074 and $107,675, according to Salary.com, with an average of $97,941. (source)
PostgreSQL calls itself βThe Worldβs Most Advanced Open Source Relational Databaseβ.
A PostgreSQL database developer works on the PostgreSQL project whereas a PostgreSQL developer works with PostgreSQL on a third-party application. Most will take the second route, for which you need to know how to access the API. (Source)
Do you want to become a PostgreSQL developer? Hereβs a learning path Iβd propose in five steps to get started:
According to ZipRecruiter, the annual income of PostgreSQL developers is between $104,000 for the bottom 25th percentile, $133,000 for the 75th Percentile, and $171,500 for the top earners.
The monthly pay ranges from $8,666 to $14,291 with an average monthly income of $10,052.
The average annual income of a RavenDB Developer is hard to estimate given the limited data availability. However, RavenDB developers are NoSQL developers who earn between $101,000 (25th percentile) and $130,500 (75th percentile) with an average of $119,105 per year in the US according to Ziprecruiter (source).
A RavenDB Developer developer creates, edits, analyzes, debugs, and supervises the development of software written in the RavenDB programming language. RavenDB is a NoSQL document-oriented database written especially for the .NET framework. (Source)
Redis (Remote Dictionary Server) is a fast, open source, in-memory, key-value data store.
As a Redis developer, you will apply and develop Redis solutions for databases, caches, message brokers, and queues.
Other use cases are chat apps, gaming leaderboards, session stores, streaming apps, and handling geospatial data sources β to name just a few. (Source)
The average annual income of a Redis developer is $113,000 in the US according to PayScale (source).
An SQL Developer creates, among other things, SQL code for database access. SQL is short for Structured Query Language that is designed to manage data stored in relational databases. (Source)
The average annual income of a SQL Developer in the US is $76,110 according to PayScale and $87,489 according to Indeed.com.
SQLite is the most used database engine in the world. SQLite implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine.
SQLite developers help clients set up, maintain, and manage an SQLite database for their applications. (Source)
The average annual income of a SQLite Developer is between $49,000 and $107,000 with an average of $64,977 per year according to PayScale (source).
FPDF is a fantastic library for working with PDF documents in PHP. It is the most popular one with a large number of plugins that enhances its core features.
Adding a watermark to a PDF document is a basic need in document editing work. Imagine that you have a project where you need to create a feature-rich PDF document editor project with the sole purpose of managing watermarks.
This PHP script will help you as a foundation code to solve your basic watermarking needs. You can use this as a base and build on top of it if you require more.
I have covered two aspects of adding watermarks.
Add a watermark to an existing PDF document.
Add a watermark to a new PDF document.
I am also presenting an online demo that watermarks a PDF document using this PHP script.
To add a watermark to an existing PDF document, I am using FPDF and FPDI libraries. FPDF is the foundation and FPDI is used to load and edit an existing document.
FPDI helps to load an existing PDF document and use it as a template in FPDF to create a document.
You need to download both FPDF and FPDI libraries and add it to the project. Refer to the project file structure image below.
Following PHP script is as simple as it gets. The Header function is used to render the PDF document page header. This is called by the AddPage function.
addWatermark is the key function responsible for creating the watermark. It sets the watermark text and performs the rotation to position it across the document. The X and Y location of where to start the watermark text and its color is defined in the Header function.
You can make adjustments by setting a smaller font, position, color, etc as per your choice.
new-pdf-watermark.php
<?php
require __DIR__ . '/fpdf/fpdf.php'; class PDF extends FPDF
{ function Header() { // setting the font, color and text for watermark $this->SetFont('Times', 'B', 48); $this->SetTextColor(140, 180, 205); $watermarkText = 'New PDF Watermark - PHP'; $this->addWatermark(35, 190, $watermarkText, 45); } function addWatermark($x, $y, $watermarkText, $angle) { $angle = $angle * M_PI / 180; $c = cos($angle); $s = sin($angle); $cx = $x * $this->k; $cy = ($this->h - $y) * $this->k; $this->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', $c, $s, - $s, $c, $cx, $cy, - $cx, - $cy)); $this->Text($x, $y, $watermarkText); $this->_out('Q'); }
} $pdf = new PDF();
$pdf->AddPage();
$pdf->SetFont('Arial', '', 12);
$pdfDocumentContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. .\n\n";
for ($i = 0; $i < 15; $i ++) { $pdf->MultiCell(0, 5, $pdfDocumentContent, 0, 'J');
}
$pdf->Output();
?>
PHP project structure
I have given the complete PHP project as a free download below. The dependent libraries FPDF and FPDI are not available in the project download zip file. You can download them from their official website and add them to your project as per the given project structure above before adding watermarks.
Question: Given a Python list stored in a variable lst. How to remove the first and last elements from the list lst?
Example: The list ['Alice', 'Bob', 'Carl', 'Dave'] stored in variable lst becomes ['Bob', 'Carl'].
Method 1: Slicing List[1:-1]
To remove the first and last elements from a Python list, use the expression lst = lst[1:-1] that uses a Python feature called slicing with the syntax variable[start:stop] to iterate over a sequence starting from the start index (included) and ending in the element at stop index (excluded). If stop is a negative integer such as -i, Python takes the i-th right-most element.
To remove the first and last elements from a Python list, you can also use the slightly more complex expression lst = lst[1:len(lst)-1] that assigns the result of the slicing operation to the list and, thereby, overwrites the original longer list. We decrement the len() function result to obtain the index of the last element that is excluded from the slice.
To remove the first element of a Python list, you can use the list.pop(0) method. To remove the last element of a Python list, you can use the list.pop() method without argument. You can call both to remove the first and the last elements if the list has at least two elements.
Here’s a minimal example:
lst = ['Alice', 'Bob', 'Carl', 'Dave']
lst.pop() # remove last
lst.pop(0) # remove first
print(lst)
# ['Bob', 'Carl']
However, for a list with less than two elements, this will raise an IndexError: pop from empty list. A simple if check can make sure that the list has at least two elements—and otherwise simply override it with the empty list.
Here’s some background info in case you want to dive deeper into this approach:
The list.pop() method removes and returns the last element from an existing list. The list.pop(index) method with the optional argument index removes and returns the element at the position index.