fbpx

Os

The os module allows us to explore operation system dependent functionality, such as manipulating and navigating file paths. One simple way we might utilize the os module is to check the current working directory (similar to typing cd in a Linux command line). For instance:

				
					import os

# Get the current working directory
cwd = os.getcwd()
print(cwd)
				
			

There is also a useful os.remove() function that allows us to delete files from folders:

				
					import os

os.remove("demofile.txt")
				
			

The code above will throw an exception if the file we are trying to remove does not exist in the folder. So, a better way may be to use the os.path module to determine if the file exists before removing it. For example:

				
					import os

if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
  print("File removed")
else:
  print("The file does not exist")

				
			

Replit Practice

Loading...