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
write() to read from the file and to write to the file.
>>> opened_file = open('file.txt')
>>> the_file_content = opened_file.read()
'Hi there! I am a .txt file!'
Because the filesystem sees renaming and moving files as being the same thing you can do it in two ways that achieve the same result:
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
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')
itertools module provides iterators that you can use in your projects. One of the commonly used method is
>>> import itertools
>>> accumulator = itertools.accumulate(range(10))
Data structures in Python are almost entirely already iterable. However, sometimes you do need a generator for the cases when the data is not iterable.
Many times you need to work with files in Python. Let’s say that you have to iterate over the content of a file for further processing. You can use for this task the
open function which returns a file object that can be iterated over line by line.
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)
Let’s say that you need to iterate over the content of a list. In order to do that you need to use the
iter function that allows you to get access to the associated iterator.
>>> list_one = [1, 2, 3, 4]
>>> iterator_one = iter(list_one)
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
>>> import datetime
>>> current_datetime = datetime.datetime.now()
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