Python课后习题-第八章 读写文件

本篇内容涵盖了Python第八章的学习要点,包括文件的读写操作,详细讲解了shelf模块中如何进行删除操作,同时介绍了正则表达式的使用,特别是其在文本查找中的可扩展应用,类似于grep的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

8.9.1 shelf 的删除-多重剪贴板

import shelve, pyperclip, sys

mcbShelf = shelve.open('F:\\python\\mcb')

if len(sys.argv) == 3 :
    if sys.argv[1].lower() == 'save' :
        mcbShelf[sys.argv[2]] = pyperclip.paste()
        print(pyperclip.paste())
    elif sys.argv[1].lower() == 'delete':
        del mcbShelf[sys.argv[2]]                     #delete one item
        print('delete1')
elif len(sys.argv) == 2 :
    if sys.argv[1].lower() == 'list' :
        pyperclip.copy(str(list(mcbShelf.keys())))
        print(str(list(mcbShelf.keys())))
        print(str(list(mcbShelf.values())))
    elif sys.argv[1] in mcbShelf:
        pyperclip.copy(mcbShelf[sys.argv[1]])
        print(mcbShelf[sys.argv[1]])
    elif sys.argv[1].lower() == 'delete':
        mcbShelf.clear()                              #delele all
        print('delete2')
mcbShelf.close()

8 .9.2 疯狂填词

import re

readFile = open('F:\\python\\madlibs.txt')
readContent = readFile.read()
readFile.close()
wordRegex = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB')		#正则表达式

print(readContent)
searchResult = wordRegex.findall(readContent)

inputResult=[]
for i in searchResult :
    if i == 'ADJECTIVE' :
        print('Enter an adjective:')
        inputResult.append(input())
    if i == 'NOUN' :
        print('Enter a noun:')
        inputResult.append(input())
    if i == 'ADVERB' :
        print('Enter a verb:')
        inputResult.append(input())
    if i == 'VERB' :
        print('Enter an adverb:')
        inputResult.append(input())


writeContent = wordRegex.sub('%s', readContent)			#通配符插入

writeFile = open('F:\\python\\madlibs_result.txt', 'w')
writeFile.write(writeContent%(tuple(inputResult)))		#通配符替换, tuple可以但是list不可以
print(writeContent%(tuple(inputResult)))
writeFile.close()

8.9.3  正则表达式查找 - 可以扩展 - grep

import os,sys,re

def viewall(path):
    path = os.path.abspath(path)
    for i in os.listdir(path):              #listdir() return relpath only
        file = os.path.join(path, i)        #join to get abspath
        if os.path.isdir(file):
            viewall(file)
        elif os.path.basename(file).endswith('.txt'):
            checkfile(file)

def checkfile(file):
    file = os.path.abspath(file)
    fileContent = open(file).readlines()
    for line in fileContent:
        if regex.search(line, re.I) != None :
            print(file + ':' + line)


if len(sys.argv) != 3 :
    print('wrong format')
    sys.exit()
    
rootPath = sys.argv[1]
regex = re.compile(sys.argv[2])

if not os.path.exists(rootPath):
    print('invalid path')
    sys.exit()

if os.path.isdir(rootPath):
    viewall(rootPath)
elif os.path.isfile(rootPath) and os.path.basename(rootPath).endswith('.txt'):
    checkfile(rootPath)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值