Category Archives: Python

How to open, read, and write text files in Python

Let’s say that you need to open, read, and write text files in Python. First you can use the open() built-in function to open the file. Once the file is opened you can use the two built-in methods read() and write() to read from the file and to write to the file.

>>> opened_file = open('file.txt')
>>> the_file_content =
>>> the_file_content
'Hi there! I am a .txt file!'

Continue reading

How to copy files using shutil module in Python

The shutil module contains many functions but two of them can be used to copy files from one location to another. To demonstrate this I created two text files named file1.txt and file2.txt.

You can copy the content of the file1.txt to the file2.txt. This way, both files will have the same content but they will still have their original names.

>>> import shutil
>>> new_file_path = shutil.copy('file1.txt', 'file2.txt')

Continue reading

How to create classes of iterators using itertools module in Python

The itertools module provides iterators that you can use in your projects. One of the commonly used method is accumulate.

>>> import itertools
>>> accumulator = itertools.accumulate(range(10))
>>> next(accumulator)
>>> next(accumulator)
>>> next(accumulator)
>>> next(accumulator)
>>> next(accumulator)
>>> next(accumulator)

Continue reading

How to extract and filter the content of an iterator in Python

Let’s say that you have an iterator and you need to list all the containing elements within it. In order to do that you can use the enumerate() function which will take an iterable object and return a list of tuples (count + value).

>>> bikes = ['Honda', 'Yamaha', 'Suzuki']
>>> bike_enum = enumerate(bikes)
>>> next(bike_enum)
(0, 'Honda')
>>> next(bike_enum)
(1, 'Yamaha')
>>> next(bike_enum)
(2, 'Suzuki')

Continue reading

How to get the current date and time in Python

Let’s say you need the current date and time from your system to place it in a Python application. For example to place the date and time as a timestamp in a blog application so the date and time when a blog article was posted will be visible on the screen.

For that, we need to import a module called datetime which contains a class with the same name datetime.

>>> import datetime
>>> current_datetime =
>>> print(current_datetime)
2017-12-11 08:18:18.685000

Continue reading

How to generate random numbers in Python

Let’s say you need to generate random numbers in Python. I need it once for an application that generates random numbers in order to create math problems to be solved by students. But being able to generate random numbers is useful in many other situations. In order to generate random numbers in Python we need to import the random module.

Continue reading