9-2
#!/user/bin/env python
# -*- coding:utf-8 -*-
F = raw_input('Enter a filename ')
N = int(raw_input('Enter lines to display '))
filename = file(F, 'r')
for eachLine in filename:
if N != 0:
print eachLine
N -= 1
filename.close()
9-3#!/user/bin/env python
# -*- coding:utf-8 -*-
filename = raw_input('Enter a filename ')
n = 0
filename = file(filename, 'r')
for eachLine in filename:
n = n + 1
filename.close()
print n
9-4#!/user/bin/env python
# -*- coding:utf-8 -*-
filename = raw_input('Enter a filename ')
n = 0
filename = file(filename, 'r')
for eachLine in filename:
print eachLine
n += 1
if n % 25 == 0:
raw_input("Press any key to continue ")
filename.close()
9-5
#!/user/bin/env python
# -*- coding:utf-8 -*-
import random
import string
srstring = string.letters
f1 = open('source.txt', 'w')
for i in range(0, 10):
name = ''
length = random.randint(5, 10)
for j in range(length):
name += random.choice(srstring)
score = random.randint(20, 100)
score = str(score)
outstring = name + ' ' + score + '\n'
f1.write(outstring)
f1.close()
f1 = open('source.txt', 'r')
sum1 = 0
n = 0
for each_line in f1:
sum1 += int(each_line.split()[1])
n += 1
print sum1, sum1 / n
f1.seek(0)
print sum(int(line.split()[1]) for line in f1)
f1.close()
9-6
#!/user/bin/env python
# -*- coding:utf-8 -*-
file1 = [line for line in file('9-1.py', 'r')]
file2 = [line for line in file('9-2.py', 'r')]
len1 = len(file1)
len2 = len(file2)
len_min = min(len1, len2)
for row in range(len_min):
if file1[row] != file2[row]:
words1 = [word for word in file1[row]]
words2 = [word for word in file2[row]]
len1 = len(words1)
len2 = len(words2)
len_min = min(len1, len2)
for colomn in range(len_min):
if words1[colomn] != words2[colomn]:
break
print 'Diff in row[%s], colomn[%s]'%((row+1),(colomn+1))
break
else:
print 'It is total same file.'
9-9
#!/user/bin/env python
import os
has=[]
nhas=[]
def doc_string():
os.chdir('C:\Python27\Lib')
cwd=os.getcwd()
#print cwd
doclist=os.listdir(cwd)
for d in doclist:
path = os.path.join(cwd,d)
#print path
if os.path.isfile(path):
h_doc=0
fp=open(path,'r')
for line in fp:
if '\'\'\'' in line:
has.append(path)
h_doc=1
break
if h_doc==0:
nhas.append(path)
fp.close()
print "doc has __doc__:",has
print "\ndoc hasn't __doc__:",nhas
doc_string()
9-12
#!/user/bin/env python
# -*- coding:utf-8 -*-
import time, getpass, hashlib, shelve
# 用字典作爲數據庫
db = shelve.open('userpw2.shelve')
# 此函數用於註冊
def sigup():
# 寫一個提示標語
prompt = '>New user sigup first: '
while True:
# 輸入賬號
user = raw_input(prompt).lower()
# 如果數據庫中已經有了賬號,提示重新輸入
if user in db:
prompt = '>The user is existing, try another.'
continue # 回到循環處繼續循環
elif not user.isalnum() or ' ' in user:
print 'Invalid: username'
continue
else:
break # 否則跳出循環
# 輸入密碼
psw = getpass.getpass()
# 把賬號和密碼加入數據庫中
timeNow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
db[user] = hashlib.md5(psw).hexdigest(), timeNow
print '>You has already sigup, return to login page.>>>'
# 此函數用於登錄
def login():
# 寫一個提示標語
prompt = '>New user sigup first(sigup) || Existing user: Enter your username\n>'
while True:
# 輸入賬號密碼
user = raw_input(prompt).lower()
if 'sigup' in user:
sigup()
psw = getpass.getpass()
# 判斷輸入密碼是否正確,正確則跳出循環,否則繼續循環
if db.has_key(user) and db.get(user)[0] == hashlib.md5(psw).hexdigest():
break
else:
prompt = '>Password or username is not right, try again.\n>New user sigup first(sigup) || Existing user enter your username\n> '
continue
timeNow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
db[user] = hashlib.md5(psw).hexdigest(), timeNow
diffTime = float(time.time() - time.mktime(time.strptime(db[user][1],'%Y-%m-%d %H:%M:%S'))) / 3600
if diffTime <= 4:
print 'You already logged in at: ', db[user][1]
print '>***Welcome, %s!***' % user
def manage():
prompt = '>(D)elete a user\n>(S)how all user\n>(O)ut put\n>(Q)uit\n>'
done = False
while not done:
# 是否要跳出選擇
chosen = False
while not chosen:
try:
choice = raw_input(prompt).strip()[0].lower()
except (EOFError, KeyboardInterrupt):
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'sdqo':
print '>Invalid option, try again!'
else:
chosen = True
if choice == 'd':
user = raw_input('>Enter the user which you want to delete: ')
if user in db:
del db[user]
print '>Remove %s ... Done!' % user
else:
print '>User has no name: %s ' % user
if choice == 's':
for user in db:
print user
if choice == 'q':
done = True
# 此函數用於展示輸入和作爲引擎
def showmunue():
# 展示你可以輸入的標語
prompt = """
(S)igup
(L)ogin
(M)anage
(Q)uit
>Enter your choice: """
# 是否要跳出循環
done = False
while not done:
# 是否要跳出選擇
chosen = False
while not chosen:
try:
choice = raw_input(prompt).strip()[0].lower()
except (EOFError, KeyboardInterrupt):
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'slmq':
print '>Invalid option, try again!'
else:
chosen = True
if choice == 'q':
done = True
if choice == 's':
sigup()
if choice == 'm':
manage()
if choice == 'l':
login()
if __name__ == '__main__':
showmunue()
db.close()
9-15
rse.ArgumentParser()
parser.add_argument("file_A")
parser.add_argument("file_B")
parser.add_argument("-c", "--copy", action="store_true",
help="copy file A to file B")
args = parser.parse_args()
if args.copy:
fileA = open(args.file_A, 'r+')
fileB = open(args.file_B, 'w+')
fileB.write(fileA.read())
fileA.close()
fileB.close()
9-16
fsource = open("4-1.txt", "r")
ftarget = open("filetest.txt", 'w+')
for line in fsource:
if len(line)-1 <= 80:
ftarget.write(line)
else:
writeline = line
while len(writeline)-1 > 80:
i = 79
while i >= 0:
if writeline[i] in [' ', ',', ':', ';', '.', '!']:
ftarget.write(writeline[0:i+1] + '\n')
writeline = writeline[i+1:]
break;
i -= 1
ftarget.write(writeline)
fsource.close()
ftarget.close()
9-17
#!/user/bin/env python
# -*- coding:utf-8 -*-
import os
def create():
filename = raw_input('Filename need:').strip()
cwd = os.getcwd()
filelist = os.listdir(cwd)
if filename in filelist:
print 'Filename already taken, try another'
else:
newfile = open(filename, 'w+')
content = raw_input('Write something:')
newfile.write(content)
newfile.close()
def display():
filename = raw_input('Filename need:').strip()
cfile = open(filename, 'r')
for row, line in enumerate(cfile):
print row, line
cfile.close()
def edit():
filename = raw_input('Filename need:').strip()
cfile = open(filename, 'r+')
linenum = raw_input('Enter the num of line you want to edit:')
buffer_file = open('test.txt', 'w+')
for row, line in enumerate(cfile):
if row == int(linenum):
line = raw_input('Edit content:')
buffer_file.write(line)
buffer_file = open('test.txt', 'r')
cfile = open(filename, 'w+')
cfile.write(buffer_file.read())
cfile.close()
buffer_file.close()
def save():
pass
def showmunue():
# 展示你可以輸入的標語
prompt = """
(C)reate a file
(D)isplay a file
(E)dit file
(S)ave
(Q)uit
>Enter your choice: """
# 是否要跳出循環
done = False
while not done:
# 是否要跳出選擇
chosen = False
while not chosen:
try:
choice = raw_input(prompt).strip()[0].lower()
except (EOFError, KeyboardInterrupt):
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'cdesq':
print '>Invalid option, try again!'
else:
chosen = True
if choice == 'q':
done = True
if choice == 'c':
create()
if choice == 'd':
display()
if choice == 'e':
edit()
if choice == 's':
save()
if __name__ == '__main__':
showmunue()
9-18
fn=raw_input("file:")
n=int(raw_input("num:").strip())
char=chr(n)
fp=open(fn,'r')
all_line=fp.readlines()
fp.close()
context=''.join(all_line)
cnt=context.count(char)
print cnt
9-19
import random
def radint_bin_file(value, counting, lens):
ran_lens = lens - counting
rans = []
n = 0
while n < ran_lens:
ran = random.randint(0, 255)
if ran == value:
continue
else:
rans.append(chr(ran))
n += 1
for i in range(counting):
rans.insert(random.randint(0, ran_lens), chr(value))
filename = open(r'radombin.txt', 'wb')
filename.write(''.join(rans))
filename.close()
radint_bin_file(65, 5, 38)
filename = open(r'radombin.txt', 'rb')
for i in filename:
print i
filename.seek(0, 0)
print len(filename.readlines()[0])
filename.close()
9-20
import gzip
import shutil
with open('filetest.txt', 'rb') as f_in, gzip.open('filetest.txt.gz', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
9-21
import zipfile
def zip_create():
zipname = raw_input('zipname: ')
myzip = zipfile.ZipFile(zipname)
myzip.close()
def zip_add():
zipname = raw_input('zipname: ')
myzip = zipfile.ZipFile(zipname, 'a')
filename = raw_input('filename: ')
myzip.write(filename)
def zip_extra():
zipname = raw_input('zipname: ')
myzip = zipfile.ZipFile(zipname, 'a')
filename = raw_input('filename: ')
myzip.extract(filename)
9-22
me, zipfile
zipname = raw_input('zipname: ')
print 'zip file size: %d bytes' % (os.stat(zipname).st_size)
myzip = zipfile.ZipFile(zipname, 'r', 8)
print 'filename\tdatetime\t\t size compress size\trate'
for info in myzip.infolist():
t = time.ctime(time.mktime(tuple(list(info.date_time) + [0, 0, 0])))
rate = float(info.compress_size) / info.file_size * 100
print '%s\t%s %d\t%d\t\t%.2f%%' % (info.filename, t,
info.compress_size, info.file_size, rate)
myzip.close()
9-23
import tarfile
def tar_create():
tarname = raw_input('tarname: ')
mytar = tarfile.open(zipname, 'w:gz')
mytar.close()
def tar_add():
tarname = raw_input('tarname: ')
mytar = tarfile.open(zipname, 'w:gz')
filename = raw_input('filename: ')
mytar.add(filename)
mytar.close()
def tar_extra():
tarname = raw_input('tarname: ')
mytar = tarfile.open(zipname, 'r:gz')
filename = raw_input('filename: ')
mytar.extractall()
mytar.close()