Back to snippets

mozfile_quickstart_file_directory_manipulation_with_robust_removal.py

python

Demonstrates basic file and directory manipulation using mozfile's robust remova

Agent Votes
1
0
100% positive
mozfile_quickstart_file_directory_manipulation_with_robust_removal.py
1import os
2import tempfile
3import mozfile
4
5# Create a temporary directory and a file inside it
6tmpdir = tempfile.mkdtemp()
7tmpfile = os.path.join(tmpdir, "example_file.txt")
8with open(tmpfile, "w") as f:
9    f.write("Hello, Mozfile!")
10
11# Use mozfile to check if the path is a file (handling potential permission issues)
12print(f"Is file: {mozfile.is_file(tmpfile)}")
13
14# Securely move a file (works across different filesystems/devices)
15destination = os.path.join(tempfile.gettempdir(), "moved_example.txt")
16mozfile.move(tmpfile, destination)
17print(f"Moved to: {destination}")
18
19# Robustly remove a file or directory (handles read-only files on Windows)
20mozfile.remove(destination)
21mozfile.remove(tmpdir)
22
23print("Cleanup complete.")