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
os.getcwd()
list files
os.listdir(directory)
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.
def getDirOrFile(file):
result = "file"
if os.path.isdir(file):
result = "directory"
return result
determine if a file exists
if os.path.exists(filename):
print("The file %s exists" % (filename))
else:
print("The file does %s not exist" % (filename))
rename a file
Files can be renamed as shown below.
os.rename(old_name, new_name)
However, if a file with the new name already exists, it will be overwritten.
delete a file
The following function deletes a file.
def delete_file(filename):
print("...deleting a file")
if os.path.isfile(filename):
os.remove(filename)
print("The file %s has been deleted" % (filename))
else:
print("The file %s does not exist" % (filename))
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:
if not os.path.exists(directory):
os.makedirs(directory)
Trying to create a directory that already exists will cause an error. Therefore, it is better to check before.