Categories
Python Answers

How to iterate over all pairs of consecutive items in a list with Python?

Sometimes, we want to iterate over all pairs of consecutive items in a list with Python.

In this article, we’ll look at how to iterate over all pairs of consecutive items in a list with Python.

How to iterate over all pairs of consecutive items in a list with Python?

To iterate over all pairs of consecutive items in a list with Python, we can use zip with a for loop.

For instance, we write:

l = [1, 7, 3, 5]
for first, second in zip(l, l[1:]):
    print(first, second)

We call zip with l and a list with l starting with the 2nd element.

Then we loop through the list of tuples returned by zip and print the first and second item in each tuple.

Therefore, we get:

1 7
7 3
3 5

Conclusion

To iterate over all pairs of consecutive items in a list with Python, we can use zip with a for loop.

Categories
Python Answers

How to find the full path of the Python interpreter?

Sometimes, we want to find the full path of the Python interpreter.

In this article, we’ll look at how to find the full path of the Python interpreter.

How to find the full path of the Python interpreter?

To find the full path of the Python interpreter, we can use the sys.executable property.

For instance, we write:

import sys

print(sys.executable)

Then print will print the path of the Python interpreter, which is something like '/opt/virtualenvs/python3/bin/python'.

Conclusion

To find the full path of the Python interpreter, we can use the sys.executable property.

Categories
Python Answers

How to read specific columns from a csv file with the csv module?

Sometimes, we want to read specific columns from a csv file with the csv module.

In this article, we’ll look at how to read specific columns from a csv file with the csv module.

How to read specific columns from a the csv file with csv module?

To read specific columns from a csv file with the csv module, we can use list comprehension.

For instance, we write:

import csv

included_cols = [1]
csv_file = 'data.csv'

with open(csv_file, 'r') as csvfile:
    reader = csv.reader(csvfile)

    for row in reader:
        content = list(row[i] for i in included_cols)
        print(content)

We define the included_cols with the index of the columns we want to read.

Then we call open to open the file according to the csv_file path.

Next, we read the lines in the CSV by calling csv.reader with csvfile.

And then we loop through the rows with a for loop.

In the loop body, we get the row entry we want to include with row[i] for i in included_cols).

And then we print that with print.

Conclusion

To read specific columns from a csv file with the csv module, we can use list comprehension.

Categories
Python Answers

How to import a CSV file into a sqlite3 database table using Python?

Sometimes, we want to import a CSV file into a sqlite3 database table using Python.

In this article, we’ll look at how to import a CSV file into a sqlite3 database table using Python.

How to import a CSV file into a sqlite3 database table using Python?

To import a CSV file into a sqlite3 database table using Python, we can use the csv and sqlite3 modules.

For instance, we write:

import csv, sqlite3

con = sqlite3.connect(":memory:") 
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);")
with open('data.csv','r') as fin:
    dr = csv.DictReader(fin)
    to_db = [(i['col1'], i['col2']) for i in dr]

cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()
con.close()

to read data from data.csv, which has:

col1,col2
1,2
3,4
5,6

We connect to the SQLite database with sqlite3.connect.

Then we call con.cursor to get a cursor.

Next we use the cursor to create a table by calling cur.execute.

Then we open the CSV with open.

We read the file by using the csv.DictReader constructor with the file fin.

And then we get the items that we want to write to the DB into a list of tuples with to_db = [(i['col1'], i['col2']) for i in dr].

Next we call cur.executemany with the insert SQL statement and to_db to insert the entries.

Finally, we call commit to commit the insertion and close to close the db connection.

Conclusion

To import a CSV file into a sqlite3 database table using Python, we can use the csv and sqlite3 modules.

Categories
Python Answers

How to parse a YAML file in Python?

Sometimes, we want to parse a YAML file in Python.

In this article, we’ll look at how to parse a YAML file in Python.

How to parse a YAML file in Python?

To parse a YAML file in Python, we can use the PyYAML package.

To install it, we run:

pip install pyyaml

Then we write:

import yaml

with open("example.yaml", "r") as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

to parse example.yaml, which has:

a list:
- 1
- 42
- 3.141
- 1337
- help
- €
a string: bla
another dict:
  foo: bar
  key: value
  the answer: 42

We open the YAML file with open with read permission.

Then we call yaml.safe_load to load the open file stream.

From print, we get:

{'a list': [1, 42, 3.141, 1337, 'help', '€'], 'a string': 'bla', 'another dict': {'foo': 'bar', 'key': 'value', 'the answer': 42}}

A yaml.YAMLError will be raised if the file can’t be parsed.

Conclusion

To parse a YAML file in Python, we can use the PyYAML package.