7) b. File Handling

What if you not only want to read and write to files but also manipulate them? For example, searching for a file in your OS, or traversing through a folder and finding out which files exist. Python 3 has a module called pathlib for this.

Note: You can do similar manipulations using a lower level os module but that is more complicated for beginners and harder for you to remember. Hence, it will not be covered here. pathlib allows you to work with files and folders easily.

One of the advantages of using pathlib over os is that paths are objects with methods relevant to file query or manipulation. Also you can just use slashes to declare paths. And it’s cross platform, meaning that you don’t have to worry about backslashes on Windows!

We will start by iterating over contents of some folder.
Note: The character “.” indicates the current folder where the program is running. Even in Windows/Linux terminal you denote the current folder where the you are with a period symbol.

1
2
3
4
5
6
7
8
from pathlib import Path

# We need to provide a path to a folder or a file.
# It can be an absolute path or a relative path
downloads_folder = Path("./Downloads")

for file_or_folder in downloads_folder.iterdir():
    print(file_or_folder)

This script will print the paths of all files and folders that are in the “Downloads” directory which in turn is within the current directory.




You can query paths for their properties.

1
2
3
4
5
6
7
8
9
10
11
12
13
from pathlib import Path

my_folder = Path("images")
my_file = Path("photos list.txt")

# Check if the path is a directory
print(my_folder.is_dir())

# Check if the path is a file
print(my_file.is_file())

# Check if path exists
print(my_file.exists())




You can also create folders or empty files (useful in some situations).

1
2
3
4
5
6
7
8
9
10
11
12
from pathlib import Path

# print current directory
print(Path().cwd())

# Create a new directory inside current directory
new_folder = Path("videos")
new_folder.mkdir()

# Create a new file inside current directory
new_file = Path("sometimes_useful_file.txt")
new_file.touch()




And you can also rename paths.
Tip: If you add the directory along with the file name then you can even end up moving the file from one folder to another!

1
2
3
4
5
6
7
8
9
10
from pathlib import Path

my_folder = Path("images")
print("current folder", my_folder.name)
my_folder.rename("photos")

# Note: The rename command can also be used to move the file to another folder
my_file = Path("c:/camera/img004.jpg")
print("current file", my_file.name)
my_file.rename("c:/camera/backup/img004.jpg")




You can even delete files and folders.

1
2
3
4
5
6
7
from pathlib import Path

useless_folder = Path("junk")
useless_folder.rmdir()

useless_file = Path("more_junk.zip")
useless_file.unlink()

Here is a summary of the important methods discussed in this chapter: