Categories
Python Answers

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

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

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

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

To read specific columns from a csv file with csv module with Python, we can loop through the rows read from the csv and then put them in a dict.

For instance, we write

import csv
from collections import defaultdict

columns = defaultdict(list)

with open("file.txt") as f:
    reader = csv.DictReader(f)
    for row in reader:
        for (k, v) in row.items():
            columns[k].append(v)

print(columns["name"])

to open file.txt.

Then we read the contents into rows with

reader = csv.DictReader(f)

Then we loop through the rows with a for loop.

And we loop through the items with another for loop.

Then we append the items to an entry in columns with key k with append to append v.

Now we can get the values of the name column with columns['name'].

Conclusion

To read specific columns from a csv file with csv module with Python, we can loop through the rows read from the csv and then put them in a dict.

Categories
Python Answers

How to find the time difference between two datetime objects in Python?

Sometimes, we want to find the time difference between two datetime objects in Python.

In this article, we’ll look at how to find the time difference between two datetime objects in Python.

How to find the time difference between two datetime objects in Python?

To find the time difference between two datetime objects in Python, we can subtract datetime objects directly.

For instance, we write

import datetime

first_time = datetime.datetime.now()
later_time = datetime.datetime.now()
difference = later_time - first_time
seconds_in_day = 24 * 60 * 60
diff = divmod(difference.days * seconds_in_day + difference.seconds, 60)

to create 2 datetimes first_time and later_time.

Then we get the difference as a timedelta object with

later_time - first_time

Then we us divmod to divide the difference.days * seconds_in_day + difference.seconds by 60 to get the number of minutes and the remainder in seconds in a tuple.

Conclusion

To find the time difference between two datetime objects in Python, we can subtract datetime objects directly.

Categories
Python Answers

How to constantly print Subprocess output while process is running with Python?

Sometimes, we want to constantly print Subprocess output while process is running with Python.

In this article, we’ll look at how to constantly print Subprocess output while process is running with Python.

How to constantly print Subprocess output while process is running with Python?

To constantly print Subprocess output while process is running with Python, we can loop through stdout and call print in the loop.

For instance, we write

from subprocess import Popen, PIPE, CalledProcessError

with Popen(cmd, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
    for line in p.stdout:
        print(line, end='')

if p.returncode != 0:
    raise CalledProcessError(p.returncode, p.args)

to call Popen with the cmd command we want to run.

Then we have a for loop that loops through p.stdout to get the output lines.

In the loop, we call print to print the line.

Conclusion

To constantly print Subprocess output while process is running with Python, we can loop through stdout and call print in the loop.

Categories
Python Answers

How to redirect ‘print’ output to a file with Python?

Sometimes, we want to redirect ‘print’ output to a file with Python.

In this article, we’ll look at how to redirect ‘print’ output to a file with Python.

How to redirect ‘print’ output to a file with Python?

To redirect ‘print’ output to a file with Python, we can set the file argument when we call print.

For instance, we write

with open('out.txt', 'w') as f:
    print('Filename:', filename, file=f)

to open the out.txt file with open.

Then we call print to set the file argument to the opened file f to save the print output to out.txt.

Conclusion

To redirect ‘print’ output to a file with Python, we can set the file argument when we call print.

Categories
Python Answers

How to profile memory usage in Python?

Sometimes, we want to profile memory usage in Python.

In this article, we’ll look at how to profile memory usage in Python.

How to profile memory usage in Python?

To profile memory usage in Python, we can use the guppy module.

To install it, we run

pip install guppy3

Then we use it by writing

from guppy import hpy

h = hpy()
print(h.heap())

to call heap to return a string with the list of items using memory.

All memory sizes are in bytes.

Conclusion

To profile memory usage in Python, we can use the guppy module.