Skip to content

Commit bed45c8

Browse files
authored
Merge pull request #306 from Rockwell70/main
Initial commit of file copying program.
2 parents bf8ae5e + 333d631 commit bed45c8

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# File copying
2+
3+
### Description
4+
5+
I built this program so I can back up my files with only new files or files that have changed since
6+
the last backup. This program recursively walks down every directory tree until it finds a file, then adds or replaces
7+
this file into the backup directory.
8+
9+
### Functionality
10+
- Directory walking
11+
- Selective file copying
12+
13+
### Instructions
14+
It uses only the standard library so can be run as is.
15+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import os
2+
import shutil
3+
4+
from contextlib import contextmanager
5+
from pathlib import Path
6+
7+
8+
@contextmanager
9+
def copy_work(working_dir, text_to_replace, replacement_text):
10+
"""
11+
Recursive function that iterates down through source directory until a file is reached. If file is newer than same
12+
file in the target directory then replaces target file with source version. If source doesn't exist in target
13+
directory then copies source file into target directory.
14+
:param replacement_text: replacement text to put into source path i.e /a/b/<replacement_text>/file
15+
:param text_to_replace: text that needs to be replaced in source path i.e /a/b/<text_to_replace>/file
16+
:param working_dir: the source directory that contains the newest files.
17+
:return: copied file
18+
"""
19+
os.chdir(working_dir)
20+
for file in Path.cwd().iterdir():
21+
if file.is_file():
22+
try:
23+
p1, p2 = os.path.getmtime(Path(file.as_posix())), os.path.getmtime(Path(
24+
f'{os.path.split(file.as_posix())[0].replace(text_to_replace, replacement_text)}/{os.path.split(file.as_posix())[1]}').as_posix())
25+
if p1 > p2:
26+
shutil.copy(Path(file).as_posix(), Path(
27+
f'{os.path.split(file.as_posix())[0].replace(text_to_replace, replacement_text)}/{os.path.split(file.as_posix())[1]}'))
28+
print(f'{Path(file).name} replaced.')
29+
except:
30+
shutil.copy(Path(file).as_posix(), Path(
31+
f'{os.path.split(file.as_posix())[0].replace(text_to_replace, replacement_text)}/{os.path.split(file.as_posix())[1]}'))
32+
print(f'{Path(file).name} added.')
33+
else:
34+
copy_work(file, text_to_replace, replacement_text)
35+

0 commit comments

Comments
 (0)