File system code in python

10 Python File System Methods You Should Know

You can write Python programs to interact with the file system to do cool stuff. How to do so isn’t always super clear.

This article is a guide for current and aspiring developers and data scientists. We’ll highlight 10 essential os and shutil commands so you can write scripts to automate interactions with the file system.

The file system is a bit like a house. Say you’re spring cleaning and you need to move boxes of notebooks from one room to another.

The boxes are like directories. They hold things. In this case, notebooks.

The notebooks are like files. You can read and write to them. You can put them in your directory boxes.

In this guide we’ll look at methods from the os and shutil modules. The os module is the primary Python module for interacting with the operating system. The shutil module also contains high-level file operations. For some reason you make directories with os but move and copy them with shutil. Go figure. 😏

Update: pathlib discussion added Feb. 16, 2019

In Python 3.4 the pathlib module was added to the standard library to improve working with file paths, and as of 3.6 is plays nicely with the rest of the standard library. The pathlib methods provide some benefits for parsing file paths over the methods we’ll discuss below — namely pathlib treats paths as objects rather than strings. Although pathlib is handy, it doesn’t have all the lower level functionality we’ll be exploring. Also, you’ll undoubtedly see the os and shutil methods below in code for years to come. So it’s definitely a good idea to be familiar with them.

Читайте также:  Assert in java package

I plan to discuss pathlib in a future article, so follow me to make sure you don’t miss it. To learn more about the pathlib

Источник

Оцените статью