Answers Extracted from PDF Content
1. Develop a program to backing Up a given Folder into a ZIP File by using
relevant modules and suitable methods.
Program using `zipfile` and `os` modules:
```python
import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number += 1
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
backupZip.write(foldername)
for filename in filenames:
newBase = os.path.basename(folder) + '_'
if filename.startswith(newBase) and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
```
2. What is the use of ZIP? How to create a ZIP folder and explain with
program example.
Use: ZIP compresses files to reduce size and group them.
Program:
```python
import zipfile
newZip = zipfile.ZipFile('new.zip', 'w')
newZip.write('example.txt', compress_type=zipfile.ZIP_DEFLATED)
newZip.close()
```
3. Explain the permanently and temporary deleting files and folders with
example.
Temporary Deletion (Safe delete):
```python
import send2trash
send2trash.send2trash('example.txt')
```
Permanent Deletion:
```python
import os, shutil
os.remove('file.txt') # delete file
os.rmdir('folder') # delete empty folder
shutil.rmtree('folder') # delete folder and contents
```
4. Explain how to save the variables using shelve and print.format() with
example.
```python
import shelve
shelf = shelve.open('mydata')
shelf['key'] = ['value1', 'value2']
shelf.close()
```
Using `print.format()`:
```python
name = "Python"
print("Language: {}".format(name))
```
6. Explain Absolute and Relative path with example?
Absolute Path: Full path from root, e.g. `C:\folder\file.txt`
Relative Path: Path relative to current working directory, e.g. `..\folder\file.txt`
Use:
```python
import os
print(os.path.abspath('file.txt')) # Absolute path
print(os.path.relpath('C:\folder\file.txt')) # Relative path
```
7. Explain with example the syntax of open (), read(), write() methods of a
file in Python. Explain the file opening modes.
```python
# Writing
with open('file.txt', 'w') as f:
f.write('Hello')
# Reading
with open('file.txt', 'r') as f:
print(f.read())
```
File Modes:
- 'r': read
- 'w': write (overwrite)
- 'a': append
- 'b': binary
- '+': read/write
8. Develop a program to sort the contents of a text file and write the
sorted contents into a separate text file.
```python
with open('data.txt', 'r') as f:
lines = f.readlines()
lines.sort()
with open('sorted.txt', 'w') as f:
f.writelines(lines)
```
9. Illustrate the following four methods of OS module. i) chdir() ii) walk()
iii) listdir() iv) getcwd().
i) `os.chdir(path)` - Change current working directory
ii) `os.walk(path)` - Walk through directory tree
iii) `os.listdir(path)` - List files in a directory
iv) `os.getcwd()` - Get current working directory