def newfile(): symbol = True while symbol: filename = raw_input('Enter a filename: ') if os.path.exists(filename): print 'file is exists.' else: symbol1 = True while symbol1: content = raw_input('Enter content(\ if content == 'q': break f1 = open(filename,'a+') f1.write(content) f1.write('\\n') f1.close() symbol = False def showfile(): symbol = True while symbol: filename = raw_input('Enter a filename: ') if not os.path.exists(filename): print 'file is not exists.' else: f1 = open(filename,'r') for line in f1: print line, f1.close() break def editfile(): symbol = True while symbol: filename = raw_input('Enter a filename: ') if not os.path.exists(filename): print 'file is not exists.' else: index = int(raw_input('edit index of line: ')) con = raw_input('Enter edit content: ') ls = [] f = open(filename,'r') ls = f.readlines() f.close()
ls[index - 1] = con + os.linesep f1 = open(filename,'w') for line in ls: f1.write(line) f1.close() symbol = False
def showmenu(): prompt = ''' Menu:
(N)ewfile (S)howfile (E)ditfile (Q)uit
Enter choice: ''' done = True while done: chosen = True while chosen: try: choice = raw_input(prompt).strip()[0].lower() except (EOFError,KeyboardInterrupt): choice = 'q' print '\\nYou picked: [%s]' % choice if choice not in 'ncesq': print 'invalid option, try again' else: chosen = False if choice == 'q':break if choice == 'n':newfile() if choice == 's':showfile() if choice == 'e':editfile()
if __name__ == '__main__': showmenu()
9–18. 搜索文件. 提示输入一个字节值(0 - 255)和一个文件名. 显示该字符在文件中出现的次数。 答案:
num = int(raw_input('Enter a number between 0 ~ 255: '))
filename = raw_input('Enter filename: ') ch = chr(num) numcount = 0
f = open(filename,'r') for line in f: numcount += line.count(ch) print numcount
9–19. 创建文件。创建前一个问题的辅助程序。创建一个随机字节的二进制数据文件,但某一特定字节会在文件中出现指定的次数。该程序接受三个参数: 1) 一个字节值( 0 - 255 );
2) 该字符在数据文件中出现的次数; 3) 数据文件的总字节长度。 你的工作就是生成这个文件,把给定的字节随机散布在文件里,并且要求保证给定字符在文件中只出现指定的次数,文件应精确地达到要求的长度。 答案:
import random
def abc(num, count, len): l = [] n = len - count for i in range(n): randomnum = random.randint(0,255) symbol = True while symbol: if randomnum == num: randomnum = random.randint(0,255) else: l.append(randomnum) symbol = False for i in range(count): l.append(num) random.shuffle(l) print l f = open('test.txt','w') f.close() for i in l: f = open('test.txt','a+') f.write('d %d' % (int(bin(i)[2:]),i)) f.write('\\n') f.close() print 'd %d' % (int(bin(i)[2:]),i)
abc(66,5,20)
9–20.压缩文件。写一小段代码,压缩/解压缩gzip或bzip格式的文件。可以使用命令行下的gzip或bzip2以及GUI程序PowerArchiver,StuffIt,或WinZip来确认你的Python支持这两个库。
答案:压缩/解压缩 import gzip
f_in = open('test.txt', 'rb')
f_out = gzip.open('test.txt.gz', 'wb') f_out.writelines(f_in) f_out.close() f_in.close()
import gzip
f = gzip.open('test.txt.gz', 'rb') f_out = open('test3.txt','wb') file_content = f.read() f_out.write(file_content) f.close() f_out.close()
9–21.ZIP归档文件。创建一个程序,可以往ZIP归档文件加入文件,或从中提取文件,有可能的话,加入创建ZIP归档文件的功能。 答案:
#!/usr/bin/env python import zipfile
z = zipfile.ZipFile('1_copy.txt.zip', mode = 'a') z.write('test2.txt') z.close() 答案:
import zipfile #创建压缩文件
def create_zipfile(zipname,filename1,filename2): z=zipfile.ZipFile(zipname,'w') z.write(filename1) z.write(filename2) z.close()
#追加文件到压缩文件中
def add_zipfile(zipname,filename): z=zipfile.ZipFile(zipname,'a') z.write(filename) z.close() #提取文件
def extract_zipfile(zipname,filename):
z=zipfile.ZipFile(zipname,'r') z.extract(filename) z.close()
if __name__=='__main__':
create_zipfile(r'test.zip',r'test.txt',r'test1.txt') add_zipfile(r'test.zip',r'test2.txt') extract_zipfile(r'test.zip',r'test.txt')
9–22.ZIP归档文件。unzip -l命令显示出的ZIP归档文件很无趣。创建一个Python脚本lszip.py,使它可以显示额外信息:压缩文件大小,每个文件的压缩比率(通过比较压缩前后文件大小),以及完成的time.ctime()时间戳,而不是只有日期和HH:MM。
提示:归档文件的date_time属性并不完整,无法提供给time.mktime()使用....这由你自己决定。 答案:
import zipfile,time
filename = raw_input('Enter filename: ') z1 = zipfile.ZipFile(filename,'r') for i in z1.infolist(): t = time.ctime(time.mktime(tuple(list(i.date_time) + [0,0,0]))) try: compress_percent = float(i.compress_size)/i.file_size * 100 print '%s\\t%d\\t%d\\t%.2f%%\\t%s\\t' % (i.filename, i.compress_size, i.file_size,\\ compress_percent, t) except: print '%s is null' % i.filename
9–23.TAR归档文件。为TAR归档文件建立类似上个问题的程序。这两种文件的不同之处在于ZIP文件通常是压缩的,而TAR文件不是,只是在gzip和bzip2的支持下才能完成压缩工作。
加入任意一种压缩格式支持。
附加题: 同时支持gzip和bzip2。 import tarfile
tar = tarfile.open('tar_file.tar','w') tar.add('test1.txt') tar.close()
tar = tarfile.open('tar_file1.tar.gz','w:gz') tar.add('test2.txt') tar.close()
tar = tarfile.open('tar_file2.tar.bz2','w|bz2') tar.add('test.txt')
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库python核心编程第二版第9章习题答案(4)在线全文阅读。
相关推荐: