|
| 1 | +--- |
| 2 | +title: File Operations Class |
| 3 | +description: It's an class where you have some functions for file Opertation |
| 4 | +author: mrcool7387 |
| 5 | +tags: python,file operation,class |
| 6 | +--- |
| 7 | + |
| 8 | + |
| 9 | +```py |
| 10 | +class FileOperations: |
| 11 | + def create_file(self, file_path: str): |
| 12 | + with open(file_path, 'w') as f: |
| 13 | + pass |
| 14 | + |
| 15 | + def delete_file(self, file_path: str): |
| 16 | + if os.path.exists(file_path): |
| 17 | + os.remove(file_path) |
| 18 | + |
| 19 | + def write_file(self, file_path: str, context: str): |
| 20 | + with open(file_path, 'w') as f: |
| 21 | + f.write(context) |
| 22 | + |
| 23 | + def move_file(self, src: str, dest: str): |
| 24 | + shutil.move(src, dest) |
| 25 | + |
| 26 | + def copy_file(self, src: str, dest: str): |
| 27 | + shutil.copy(src, dest) |
| 28 | + |
| 29 | + def get_file_size(self, file_path: str): |
| 30 | + return os.path.getsize(file_path) if os.path.isfile(file_path) else 0 |
| 31 | + |
| 32 | + def get_file_extension(self, file_path: str): |
| 33 | + return os.path.splitext(file_path)[1] |
| 34 | + |
| 35 | + def zip_files(self, files: list[str], zip_name: str): |
| 36 | + with zipfile.ZipFile(zip_name, 'w') as zf: |
| 37 | + for file in files: |
| 38 | + zf.write(file) |
| 39 | + |
| 40 | + def extract_zip(self, zip_name: str, extract_to: str): |
| 41 | + with zipfile.ZipFile(zip_name, 'r') as zf: |
| 42 | + zf.extractall(extract_to) |
| 43 | + |
| 44 | +# Usage |
| 45 | +fo = FileOperations() |
| 46 | + |
| 47 | +fo.create_file('./notes/note1.txt') |
| 48 | +fo.create_file('./note2.txt') |
| 49 | + |
| 50 | +fo.write_file('./notes/note1.txt', 'Very Important Notes!') |
| 51 | + |
| 52 | +fo.zip_files(['./notes/note1.txt', './note2.txt'], 'notes.zip') |
| 53 | + |
| 54 | +fo.delete_file('./notes/note1.txt') |
| 55 | +``` |
0 commit comments