Skip to content

Commit 3c722f1

Browse files
committed
Chapter 9 finished
1 parent efb40d6 commit 3c722f1

12 files changed

+198
-0
lines changed

09-organize-file/README.md

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
* shutil
2+
shell工具
3+
import shutil
4+
5+
* send2trash
6+
将文件夹和文件发送到垃圾箱或回收站
7+
pip install send2trash
8+
9+
* zipfile
10+
import zipfile

09-organize-file/backupToZip.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#! python3
2+
# backupToZip.py
3+
# Copies an entire folder and its contents into
4+
# a zip file whose filename increments.
5+
6+
import zipfile, os
7+
8+
def backupToZip(folder):
9+
# Backup the entire contents of "folder" into a zip file.
10+
11+
folder = os.path.abspath(folder) # make sure folder is absolute
12+
13+
# Figure out the filename this code should used based on
14+
# what files already exist.
15+
number = 1
16+
while True:
17+
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
18+
if not os.path.exists(zipFilename):
19+
break
20+
number = number + 1
21+
22+
# Create the zip file.
23+
print('Creating %s...' % (zipFilename))
24+
backupZip = zipfile.ZipFile(zipFilename, 'w')
25+
26+
# Walk the entire folder tree and compress the files in each folder.
27+
for foldername, subfolders, filenames in os.walk(folder):
28+
print('Adding files in %s...' % (foldername))
29+
# Add the current folder to the ZIP file.
30+
backupZip.write(foldername)
31+
32+
# Add all the files in this folder to the ZIP file.
33+
for filename in filenames:
34+
if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
35+
continue # don't backup the backup ZIP files
36+
backupZip.write(os.path.join(foldername, filename))
37+
backupZip.close()
38+
print('Done.')
39+
40+
41+
backupToZip('C:\\delicious')

09-organize-file/copy.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import os
2+
import sys
3+
import shutil
4+
5+
def copy(suffix, src, dst):
6+
# Create dst directory
7+
if not os.path.exists(dst):
8+
os.mkdir(dst)
9+
10+
# list all files
11+
try:
12+
for dirpath, dirnames, filenames in os.walk(src):
13+
#print(dirpath, dirnames, filenames)
14+
for filename in filenames:
15+
if filename.endswith('.'+suffix):
16+
print(os.path.join(dirpath, filename))
17+
# copy files with pointed suffix to dst
18+
shutil.copy(os.path.join(dirpath, filename), dst)
19+
except shutil.SameFileError:
20+
print("Finished copying file.")
21+
22+
copy('py', '.', 'pyfiles')

09-organize-file/createZipFile.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import os
2+
import zipfile
3+
4+
newZip = zipfile.ZipFile('new.zip', 'w')
5+
newZip.write('README.md', compress_type=zipfile.ZIP_DEFLATED)
6+
newZip.close()

09-organize-file/demo/spam001.txt

Whitespace-only changes.

09-organize-file/demo/spam003.txt

Whitespace-only changes.

09-organize-file/filesize.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import os
2+
import shutil
3+
4+
def search(dir, size):
5+
# dir exists
6+
if not os.path.exists(dir):
7+
print('Directory ' + dir + ' not exists.')
8+
9+
# list all files in dir
10+
for dirpath, dirnames, filenames in os.walk(dir):
11+
for filename in filenames:
12+
filepath = os.path.join(dirpath, filename)
13+
filesize = os.path.getsize(filepath)
14+
if filesize > size:
15+
print(str(filesize).ljust(16), filepath)
16+
# if filesize is bigger than size, print it's path
17+
18+
search('E:\\', 1024*1024*1024)

09-organize-file/renameDates.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#! python3
2+
# renameDates.py - Renames filenames with American MM-DD-YYYY date format
3+
# to European DD-MM-YYYY.
4+
5+
import shutil, os, re
6+
7+
# Create a regex that matches files with the American date format.
8+
datePattern = re.compile(r"""^(.*?) # all text before the date
9+
((0|1)?\d)- # one or two digits for the month
10+
((0|1|2|3)?\d)- # one or two digits for the day
11+
((19|20)\d\d) # four digits for the year (must start with 19 or 20)
12+
(.*?)$ # all text after the date
13+
""", re.VERBOSE)
14+
15+
# Loop over the files in the working directory.
16+
for amerFilename in os.listdir('.'):
17+
mo = datePattern.search(amerFilename)
18+
19+
# Skip files without a date.
20+
if mo == None:
21+
continue
22+
23+
# Get the different parts of the filename.
24+
beforePart = mo.group(1)
25+
monthPart = mo.group(2)
26+
dayPart = mo.group(4)
27+
yearPart = mo.group(6)
28+
afterPart = mo.group(8)
29+
30+
# Form the European-style filename.
31+
euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart
32+
33+
# Get the full, absolute file paths.
34+
absWorkingDir = os.path.abspath('.')
35+
amerFilename = os.path.join(absWorkingDir, amerFilename)
36+
euroFilename = os.path.join(absWorkingDir, euroFilename)
37+
38+
# Rename the files.
39+
print('Renaming "%s" to "%s"...' % (amerFilename, euroFilename))
40+
#shutil.move(amerFilename, euroFilename) # uncomment after testing

09-organize-file/send2trashDemo.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import send2trash
2+
3+
baconFile = open('bacon.txt', 'a')
4+
baconFile.write('Bacon is not a vegetable.')
5+
baconFile.close()
6+
7+
send2trash.send2trash('bacon.txt')

09-organize-file/sequence.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import os
2+
import shutil
3+
import re
4+
5+
def sequence(dir, prefix):
6+
# dir exists
7+
if not os.path.exists(dir):
8+
print('Directory not exists.')
9+
return
10+
11+
# list all file and get the number of files with prefix
12+
filenum = 0
13+
filelist = []
14+
for file in os.listdir(dir):
15+
if file.startswith(prefix):
16+
filenum += 1
17+
filelist.append(file)
18+
filelist.sort()
19+
20+
# rename file
21+
print(filelist)
22+
for i in range(filenum):
23+
srcfile = os.path.join(dir, filelist[i])
24+
dstfile = os.path.join(dir, prefix + '%03d'%(i+1) + '.txt')
25+
if srcfile != dstfile:
26+
print(srcfile, dstfile)
27+
shutil.move(srcfile, dstfile)
28+
29+
sequence('demo', 'spam')

09-organize-file/traverseDir.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import os
2+
3+
for folderName, subfolders, filenames in os.walk('E:\\git\\AutomatePython'):
4+
print('The current folder is ' + folderName)
5+
6+
for subfolder in subfolders:
7+
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
8+
for filename in filenames:
9+
print('FILE INSIDE ' + folderName + ': ' + filename)
10+
11+
print()

09-organize-file/zipfileDemo.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import os
2+
import zipfile
3+
4+
os.chdir('E:\\')
5+
exampleZip = zipfile.ZipFile('mupdf-1.9a-windows.zip')
6+
print(exampleZip.namelist())
7+
8+
spamInfo = exampleZip.getinfo('mupdf-1.9a-windows/COPYING.txt')
9+
print(spamInfo.file_size)
10+
print(spamInfo.compress_size)
11+
12+
print('Compressed file is %sx smaller!', (round(spamInfo.file_size/spamInfo.compress_size, 2)))
13+
# exampleZip.extractall()
14+
exampleZip.close()

0 commit comments

Comments
 (0)