Using os
Using os to Modify Files¶
The os library will allow you to make certain changes to your file system or modify files which can make your life much easier when you start doing things like writing hundreds of files down. Let’s begin with a simple example. If you want to make a folder in your current directory, you can call os.mkdir with the folder name.
import os
#Create a folder called Test
os.mkdir("Test")
Keep in mind if you try to create the directory a second time it will throw an error because it already exists
os.mkdir("Test")
Listing File Contents¶
You are also able to list a directory's contents to better understand where you are. The os.listdir function takes a path and returns the contents in that path.
#List the contents of the current directory
print(os.listdir("."))
#List the contents of the Test directory
print(os.listdir("./Test"))
Removing and Renaming Files¶
Remove can be done with os.remove for files or os.rmdir for directories. The function os.rename takes first a path to a current file and then the new name and renames it to that.
#Remove the first test data
os.remove("TestData.csv")
#Rename the second test data set
os.rename("TestData2.csv", "TestData.csv")
#List the directory contents
print(os.listdir("."))
#Remove both the new file and the new directory
os.remove("TestData.csv")
os.rmdir("Test")
#List the directory
print(os.listdir("."))