Categories
Python Answers

How to check if a list is empty with Python?

Sometimes, we want to check if a list is empty with Python.

In this article, we’ll look at how to check if a list is empty with Python.

How to check if a list is empty with Python?

To check if a list is empty with Python, we can use the not operator.

For instance, we write:

a = []
if not a:
    print("List is empty")

We put not before a to check if a is empty.

Since this is True, we see 'List is empty' printed.

This works because empty lists are falsy.

Conclusion

To check if a list is empty with Python, we can use the not operator.

Categories
Python Answers

How to use a decimal range() step value with Python?

Sometimes, we want to use a decimal range() step value with Python.

In this article, we’ll look at how to use a decimal range() step value with Python.

How to use a decimal range() step value with Python?

To use a decimal range() step value with Python, we can use list comprehension with range.

For instance, we write:

l = [x * 0.1 for x in range(0, 10)]
print(l)

to create a list of numbers from 0, 0.1, 0.2, … all the way to 0.9.

We create an iterator with range from 0 and 10 to create an iterator that returns 0 to 9.

And then we multiply those entries by 0.1

Therefore, l is [0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9].

Conclusion

To use a decimal range() step value with Python, we can use list comprehension with range.

Categories
Python Answers

How to merge lists into a list of tuples with Python?

Sometimes, we want to merge lists into a list of tuples with Python.

In this article, we’ll look at how to merge lists into a list of tuples with Python.

How to merge lists into a list of tuples with Python?

To merge lists into a list of tuples with Python, we can use the zip and list functions.

For instance, we write:

list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
zipped = list(zip(list_a, list_b))
print(zipped)

We call zip with list_a and list_b to merge the 2 lists together into a iterator with tuples that are each an with an entry from each of the lists.

Then we call list to convert the iterator to a list of tuples.

Therefore, zipped is [(1, 5), (2, 6), (3, 7), (4, 8)].

Conclusion

To merge lists into a list of tuples with Python, we can use the zip and list functions.

Categories
Python Answers

How to delete a specific line in a file with Python?

Sometimes, we want to delete a specific line in a file with Python.

In this article, we’ll look at how to delete a specific line in a file with Python.

How to delete a specific line in a file with Python?

To delete a specific line in a file with Python, we can read the file with open and readlines.

Then we open the file again with write permission with open, loop through each line to find the lines that we want to include and write them back to the file.

For instance, if our file has:

yourfile.txt

foo
bar
nickname_to_delete
baz

Then we write:

with open("yourfile.txt", "r") as f:
    lines = f.readlines()
with open("yourfile.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != "nickname_to_delete":
            f.write(line)

to open the file with read permission and read the lines in the file with:

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

Then we open the file with write permission, loop through each line and write the lines that we want to include in the file with:

with open("yourfile.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != "nickname_to_delete":
            f.write(line)

Calling f.write clear the file and only write the lines we want to include.

Now yourfile.txt is:

foo
bar
baz

Conclusion

To delete a specific line in a file with Python, we can read the file with open and readlines.

Then we open the file again with write permission with open, loop through each line to find the lines that we want to include and write them back to the file.

Categories
Python Answers

How to convert JSON to CSV with Python?

Sometimes, we want to convert JSON to CSV with Python.

In this article, we’ll look at how to convert JSON to CSV with Python.

How to convert JSON to CSV with Python?

To convert JSON to CSV with Python, we can use Pandas.

For instance, if our JSON file has:

test.json

[
  {
    "pk":22,
    "model":"auth.permission",
    "fields":{
      "codename":"add_logentry",
      "name":"Can add log entry",
      "content_type":8
    }
  },
  {
    "pk":23,
    "model":"auth.permission",
    "fields":{
      "codename":"change_logentry",
      "name":"Can change log entry",
      "content_type":8
    }
  },
  {
    "pk":24,
    "model":"auth.permission",
    "fields":{
      "codename":"delete_logentry",
      "name":"Can delete log entry",
      "content_type":8
    }
  },
  {
    "pk":4,
    "model":"auth.permission",
    "fields":{
      "codename":"add_group",
      "name":"Can add group",
      "content_type":2
    }
  },
  {
    "pk":10,
    "model":"auth.permission",
    "fields":{
      "codename":"add_message",
      "name":"Can add message",
      "content_type":4
    }
  }
]

Then we write:

import pandas as pd
from pathlib import Path
import json

p = Path('test.json')
with p.open('r', encoding='utf-8') as f:
    data = json.loads(f.read())

df = pd.json_normalize(data)
df.to_csv('test.csv', index=False, encoding='utf-8')

We create a Path instance with the path of the JSON file.

Then we call p.open with 'r' to read the JSON file.

Next, we call json.loads to load the JOSN file into JSON.

Next, we call pd.json_normalize with the JSON data for the file to flatten it.

Then we call df.to_csv with the file path of the file to save to and the encoding to save the CSV file.

Therefore, test.csv has:

pk,model,fields.codename,fields.name,fields.content_type
22,auth.permission,add_logentry,Can add log entry,8
23,auth.permission,change_logentry,Can change log entry,8
24,auth.permission,delete_logentry,Can delete log entry,8
4,auth.permission,add_group,Can add group,2
10,auth.permission,add_message,Can add message,4

Conclusion

To convert JSON to CSV with Python, we can use Pandas.