|
1 | 1 | ---
|
2 | 2 | title: File Operations Class
|
3 |
| -description: It's an class where you have some functions for file Opertation |
| 3 | +description: It's an class where you have some functions for file Operation |
4 | 4 | author: mrcool7387
|
5 | 5 | tags: python,file operation,class
|
6 | 6 | ---
|
7 | 7 |
|
8 | 8 |
|
9 | 9 | ```py
|
| 10 | +import zipfile |
| 11 | +import os |
| 12 | +import shutil |
| 13 | + |
10 | 14 | class FileOperations:
|
11 | 15 | def create_file(self, file_path: str):
|
| 16 | + """Creates an empty File""" |
12 | 17 | with open(file_path, 'w') as f:
|
13 | 18 | pass
|
14 | 19 |
|
15 | 20 | def delete_file(self, file_path: str):
|
| 21 | + """Deletes a File""" |
16 | 22 | if os.path.exists(file_path):
|
17 | 23 | os.remove(file_path)
|
18 | 24 |
|
19 | 25 | def write_file(self, file_path: str, context: str):
|
| 26 | + """Writes some text to a file. '\n' is used fo a new Line""" |
20 | 27 | with open(file_path, 'w') as f:
|
21 | 28 | f.write(context)
|
22 | 29 |
|
23 | 30 | def move_file(self, src: str, dest: str):
|
| 31 | + """Moves a File form its Source to it's destination""" |
24 | 32 | shutil.move(src, dest)
|
25 | 33 |
|
26 | 34 | def copy_file(self, src: str, dest: str):
|
| 35 | + """Copies a File form its Source to it's destination""" |
27 | 36 | shutil.copy(src, dest)
|
28 | 37 |
|
29 | 38 | def get_file_size(self, file_path: str):
|
| 39 | + """Returns the File size of the selected File""" |
30 | 40 | return os.path.getsize(file_path) if os.path.isfile(file_path) else 0
|
31 | 41 |
|
32 | 42 | def get_file_extension(self, file_path: str):
|
| 43 | + """Returns the Type/Extension of the selected File""" |
33 | 44 | return os.path.splitext(file_path)[1]
|
34 | 45 |
|
35 | 46 | def zip_files(self, files: list[str], zip_name: str):
|
| 47 | + """Compresses some selected Files, don't forget the '.zip' at the end of the ZIP-File-Name""" |
36 | 48 | with zipfile.ZipFile(zip_name, 'w') as zf:
|
37 | 49 | for file in files:
|
38 | 50 | zf.write(file)
|
39 | 51 |
|
40 | 52 | def extract_zip(self, zip_name: str, extract_to: str):
|
| 53 | + """Extracts from a selected ZIP File to a Destination""" |
41 | 54 | with zipfile.ZipFile(zip_name, 'r') as zf:
|
42 | 55 | zf.extractall(extract_to)
|
43 | 56 |
|
|
0 commit comments