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.

Categories
Python Answers

How to check if string input is a number with Python?

Sometimes, we want to check if string input is a number with Python.

In this article, we’ll look at how to check if string input is a number with Python.

How to check if string input is a number with Python?

To check if string input is a number with Python, we can use the string’s isnumeric method.

For instance, we write:

a = input()
isnumeric = a.isnumeric()
print('is numeric' if isnumeric else 'not numeric')

We call input to get user input and assign the input value to a.

Then we call isnumeric on a to check if it’s numeric.

If it is, True is returned. Otherwise, it returns False.

Therefore, if we enter numbers, we see 'is numeric'. Otherwise, 'not numeric' is printed.

Conclusion

To check if string input is a number with Python, we can use the string’s isnumeric method.

Categories
Python Answers

How to download image using Python requests library?

Sometimes, we want to download image using Python requests library.

In this article, we’ll look at how to download image using Python requests library.

How to download image using Python requests library?

To download image using Python requests library, we can use the requests.get method to make a GET request.

Then we call shutil.copyfileobj to save the file to disk.

For instance, we write:

import requests
import shutil

url = 'https://i.picsum.photos/id/926/200/300.jpg?hmac=jlGQWyYJAmrBGxcsX5Uwr_J1N3bMHU46d3660T6emao'
path = 'photo.jpg'

r = requests.get(url, stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

We define the url to get the image from and the path to save the image to.

Then we call requests.get with the url and stream set to True to make the request.

Then if r.status_code is 200, then we call open to open the file path with 'wb' permission to write the file to the path whether it exists or not.

Then we set r.raw.decode_content to True to decode the file content.

And finally, we call shutil.copyfileobj with r.raw to save the content to file f.

Now we should see the photo displayed when we open photo.jpg.

Conclusion

To download image using Python requests library, we can use the requests.get method to make a GET request.

Then we call shutil.copyfileobj to save the file to disk.