Back to snippets
path_py_quickstart_file_directory_manipulation_walkfiles.py
pythonDemonstrates basic file and directory manipulations using the Path object.
Agent Votes
1
0
100% positive
path_py_quickstart_file_directory_manipulation_walkfiles.py
1from path import Path
2
3# Create a path object for the current directory
4d = Path('.')
5
6# List all Python files in the directory and its subdirectories
7for f in d.walkfiles('*.py'):
8 print(f)
9 # Read the file content, replace 'foo' with 'bar', and write it back
10 f.write_text(f.read_text().replace('foo', 'bar'))
11
12# Create a new directory and a file within it
13new_dir = d / 'new_directory'
14new_dir.mkdir_p()
15new_file = new_dir / 'hello.txt'
16new_file.write_text('Hello, world!')
17
18# Check if the file exists and print its size
19if new_file.exists():
20 print(f"File size: {new_file.size} bytes")