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.

Categories
Python Answers

How to create an empty list in Python with certain size?

To create an empty list in Python with certain size, we can use the * operator.

For instance, we write:

l = [None] * 10
print(l)

We create a list with 10 None entries with [None] * 10.

Therefore, l is [None, None, None, None, None, None, None, None, None, None].

Categories
Python Answers

How to get the full path of the current file’s directory with Python?

Sometimes, we want to get the full path of the current file’s directory with Python.

In this article, we’ll look at how to get the full path of the current file’s directory with Python.

How to get the full path of the current file’s directory with Python?

To get the full path of the current file’s directory with Python, we can use the pathlib module.

To get the directory of the script being run, we write:

import pathlib

p = pathlib.Path(__file__).parent.resolve()
print(p)

Then p is something like '/home/runner/ShockingRosyGui'.

To get the current working directory, we write:

import pathlib

p = pathlib.Path().resolve()
print(p)

We call resolve on the Path instance to return the current working directory.

Conclusion

To get the full path of the current file’s directory with Python, we can use the pathlib module.

Categories
Python Answers

How to find an item in a list in Python?

Sometimes, we want to find an item in a list in Python.

In this article, we’ll look at how to find an item in a list in Python.

How to find an item in a list in Python?

To find an item in a list in Python, we can use list comprehension.

For instance, we write:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
matches = [x for x in lst if x > 6]
print(matches)

to return all the entries in lst that are bigger than 6.

We specify the condition of the items to include with the returned list with if x > 6.

And we specify the list to filter with x for x in lst.

Therefore, matches is [7, 8, 9].

Conclusion

To find an item in a list in Python, we can use list comprehension.