זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/python/lessons/files-lab
זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/python/lessons/files-lab
תשובה לתרגיל 2 תרגול קבצים
"""
Answer 11 Q 2
"""
import sys
import itertools
if len(sys.argv)!=4:
print "Must to enter name of 3 files"
sys.exit()
with open(sys.argv[1],"r") as fin1:
with open(sys.argv[2],"r") as fin2:
with open(sys.argv[3],"w") as fout:
new_lines=itertools.izip_longest(fin1,fin2)
for z in new_lines:
for line in z:
if line is None:continue
if line[-1] != "\n": line = line + "\n"
fout.write(line)
print "The file {} is created succesufly".format(sys.argv[3])
לייק 1
תשובה לתרגילך 3 בתרגול קבצים פייתון
"""
Answer 11.3
"""
import csv
total=0
with open("csvTest.csv","rb") as fcsv:
spamredear=csv.reader(fcsv)
for row in spamredear:
total=total+int(row[1])
print total
לייק 1
תרגיל 1: (עם הדרישות לשני הבונוסים)
import sys,os,argparse
if len(sys.argv[1:]) == 2:
(src,dest)=sys.argv[1:]
if not os.path.isfile(src):
print "Source file not exsist pls try again"
sys.exit(1)
else:
if not os.path.exists(dest):
print "destention file:%s not esist! its will be created now..." %(dest)
newf =open(dest, "w")
newf.close()
with open(src,"r") as fin:
with open(dest,"w") as fout:
for line in fin:
fout.write(line)
elif len(sys.argv[1:])==3:
(src,dest,newfile)=sys.argv[1:]
if os.path.exists(src) and os.path.exists(dest):
if not (os.path.exists(newfile)):
print "third file not exsist %s its will be created now... " %(newfile)
newf=open(newfile,"w")
newf.close()
with open(src,"r") as fin:
with open(newfile,"w") as fout:
for line in fin:
fout.write(line)
with open(dest,"r") as fin:
with open(newfile,"a") as fout:
for line in fin:
fout.write(line)
else:
print "one of your src or dest path file not exsits pls checked again.."
sys.exit(1)
elif len(sys.argv)>4:
print "pls enter src and dest paths and optional for third file..... "
תרגיל2:
import sys,itertools
(src1,src2,dest)=sys.argv[1:]
newfile = open(dest,"w")
newfile.close
with open(src1,"r") as txt1:
with open(src2,"r") as txt2:
lines=list(itertools.izip_longest(txt1,txt2))
with open(dest,"a") as txt3:
for i in range(len(lines)):
for word in lines[i]:
txt3.write(word)
פתרון שלי לתרגיל 3:
import csv,sys
total=0
(csvpath)=sys.argv[1]
with open(csvpath, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
for item in row:
if item.isdigit():
total+=int(item)
print total
הי Kobiedri76,
נראה טוב - אם יש זמן הייתי משפר את תרגיל 1 כי נראה שיש שם הרבה קוד כפול בין ה elif-ים. נדמה לי שיהיה מועיל להגדיר משתנה נפרד עבור ״סוג ההתנהגות״ (שייקבע לפי האורך של argv) ולשאול עליו רק פעם אחת מתוך הקוד.