קורס Python שיעור תרגול מודולים


זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/python/lessons/modules-lab
"""
answer 10.3
"""
import argparse
import os

from typing import List, Any

parser =argparse.ArgumentParser(description='Process the root path and the size of the files to deletes')
parser.add_argument("Path", help='an Root Path for find all the files if is more of the Size parameter')
parser.add_argument("Size" ,type=int ,help='an Size of the file in the byte.')

args = parser.parse_args()

removeFiles=[]  # type: List[Any]

for root,dirs,files in os.walk(args.Path):
    for name in files:
        statinfo = os.stat(name)
        if statinfo.st_size < args.Size: continue
        
        print name
        removeFiles.append(name)

countRemoveFiles=  len(removeFiles)      
if countRemoveFiles>0:
    print "Find %:d Files (size is more from %:d  bytes : do you wont to remoe it ? (Y/N))"
    toRemove=raw_input()
    if toRemove='N':exit()
    
    for name in removeFiles:
        os.remove(name)

הי,

כדי לצאת מתוכנית מומלץ להשתמש בפקודה:

sys.exit()

הפקודה exit נועדה לצאת מהסביבה האינטרקטיבית ולא תמיד תהיה זמינה בתוכניות.

בנוסף הקונבנציה בפייתון היא להשתמש באותיות קטנות עבור ארגומנטים ב argparse ושמות משתנים. כשיש שם משתנה שלוקח יותר ממילה אחת נשתמש בקו תחתי להפריד למשל:

remove_files
count_remove_files
to_remove

חוץ מזה פיתרון מעולה

"""
Answer 11 Q 1
"""
import sys
import os.path

#Cheek if argument is ok
if len(sys.argv) <3:
    print "Error: You Must to set minimum 2 argument of name of files to copy to the last argument"
    sys.exit()
#cheek if the file is exits
for fname in sys.argv[1:-1]:
    if not os.path.isfile(fname):
        print "The file '{}' issnot exist".format(fname)
        sys.exit()

with open(sys.argv[-1],"a") as fout:
    for fname in sys.argv[1:-1]:
        with open(fname,"r") as fin:
            for line in fin:
                fout.write(line)
            fout.write("\n")


"""
answer 10.3
"""
import argparse
import os

from typing import List, Any

parser =argparse.ArgumentParser(description='Process the root path and the size of the files to deletes')
parser.add_argument("Path", help='an Root Path for find all the files if is more of the Size parameter')
parser.add_argument("Size" ,type=int ,help='an Size of the file in the byte.')

args = parser.parse_args()

remove_files=[]  # type: List[Any]

for root,dirs,files in os.walk(args.Path):
    for name in files:
        statinfo = os.stat(name)
        if statinfo.st_size < args.Size: continue

        print name
        remove_files.append(name)

count_remove_files=  len(remove_files)
if count_remove_files>0:
    print "Find %:d Files (size is more from %:d  bytes : do you wont to remoe it ? (Y/N))"
    to_remove=raw_input()
    if to_remove='N':exit()

    for name in remove_files:
        os.remove(name)





הי,

שווה לציין שאפשר להעביר את שורת השגיאה כפרמטר ל sys.exit, כלומר:

sys.exit('The file {} does not exist'.format(name))

בנוסף הייתי משקיע עוד שתיים-שלוש שורות בהגדרת משתנים עם שמות משמעותיים למשל:

source_files = sys.argv[1:-1]
destination_file = sys.argv[-1]

זה יכול להפוך את התוכנית להרבה יותר ברורה. כתבתי על זה קצת יותר באריכות עם עוד דוגמא כאן: