PDF Based Python Answers
PDF Based Python Answers
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
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))
```
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()