Python challenge: Performing file operations
This blog post demonstrates how different file operations can be performed in Python. For starters the focus is on the following:
- get the current working directory
- list files
- determine wether a file is a file or directory
- determine if a file exists
- rename a file
- delete a file
- create a directory
Get the current work directory
list files
determine wether a file is a file or directory
The following function returns “file”, if the file is an actual file or “directory” if it is a directory.
determine if a file exists
rename a file
Files can be renamed as shown below.
However, if a file with the new name already exists, it will be overwritten.
delete a file
The following function deletes a file.
Trying to delete a non-existing file will cause an error, so it is better to check prior to deleting it.
create a directory
The following creates a directory:
Trying to create a directory that already exists will cause an error. Therefore, it is better to check before.