python学习23_目录习题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习23_目录习题相关的知识,希望对你有一定的参考价值。

目录操作
习题1:读一个文件,包含英文句子,请统计共多少个不重复的单词,#并且在另外一个文件中打印每个单词以及它的出线次数

#encoding =utf-8
import string
words = ""
words_dict ={}
with open("e:\python\a.txt") as file_obj:
    for line in file_obj:
        for v in line:
            if  not v.isalpha():

                line = line.replace(v," ")
        words += line

word_list = words.split()
print("不重复的单词个数:",len(set(word_list)))
for word in word_list:
    if words_dict.get(word) is None:
        words_dict[word] =1
    else:
        words_dict[word] += 1

with open("e:\python\101401.txt","w") as file_obj:
    for k,v in words_dict.items():
        file_obj.write("%s出现%d次
" %(str(k),v))

习题2:写个记账程序,每天收入多少,支出多少,总额剩多少,使用序列化方式保存信息

import pickle
fp = open("e:\a.txt","rb")
try:
    income=pickle.load(fp)
    spend=pickle.load(fp)
    deposit=pickle.load(fp)
except:
    income = []
    spend = []
    deposit= 0
fp.close()

#value|specification
while 1:
    content=input("请输入指令:")
    if content.find("exit")!=-1:
        break

    if content.find("|")==-1:
        print("data?format?is?value|specification")
        print("please?input?again!")
        continue

        value = content.split("|")[0]
        try:
            value=float(value)
        except:
            print("data?format?is?value|specification")
            print("data?format?is?value?must?be?a?number")

        if value>0:
            income.append(content)
            deposit+=value
        elif value==0:
            print("空间有限,不存0")
        else:
            spend.append(content[1:])
            deposit+=value

print(income)
print(spend)
print(deposit)

fp=open("e:\a.txt","wb")
pickle.dump(income,fp)
pickle.dump(spend,fp)
pickle.dump(deposit,fp)
fp.close()

方式2:
#encoding=utf-8

import pickle
income = []
spend = []
deposit = 0.0

while 1:
    command = input("请输入收入、支出和金额,如: 支出>50,输入q退出: ")
    if command.lower() == "q":
        break
    try:
        amount = float(command.split(">")[1])
    except Exception as e:
        print("输入错误,请重新输入")
        continue
    else:
        type = command.split(">")[0]
        if type == "收入":
            income.append(amount)
            deposit += amount
        elif type == "支出":
            if deposit - abs(amount) >= 0:
                spend.append(abs(amount))
                deposit -= amount
            else:
                print("余额不足!")

print("收入:",income)
print("支出:",spend)
print("余额:",deposit)

file_obj = open("e:\in_out.txt","wb")

pickle.dump(income,file_obj)
pickle.dump(spend,file_obj)
pickle.dump(spend,file_obj)
file_obj.close()

习题3:数据分析需求:每行内容需要生成以每行首年月日为名称的文件,文件内容写入|0|后的所有行内容(也包括|0| )

20160215000148|0|collect info job start|success|
20160215000153|0|collect info jobend|success|resultcode = 0000
20160216000120|0|collect info job start|success|
20160216000121|0|collect info jobend|success|resultcode = 0000
20160217000139|0|collect info job start|success|
20160217000143|0|collect info jobend|success|resultcode = 0000

#encoding =utf-8
with open("e:\python\a.txt") as file_obj:
    for line in file_obj:
        with open(line[:14] + ".txt","w") as fp:
            fp.write(line[14:])

习题4:删除目录下所有的.txt文件
#encoding =utf-8
import os
os.chdir("e:\python1")
for file in os.listdir():
    if ".txt" in file:
        os.remove(file)

习题5:在当前目录下,找到1小时内新建的所有文件。
算法:
取出某个目录内,1小时内新建的所有文件名。

算法:遍历这个目录,取到所有的文件每个文件用stat取到创建时间用创建时间和当前时间去比对,是否小于3600放到一个列表里面

#encoding =utf-8
import os
import time
os.chdir("e:\python")
result = []
for file in os.listdir():
    if os.path.isfile(file):
        c_time = os.stat(file).st_ctime
        if time.time() - c_time < 3600:
            result.append(file)

print(result)

习题6:小练习,把所有的txt文件干掉。新建一个空的子目录xxx,放在某个层级下,,把它删掉
方式1:
#encoding =utf-8

import os
dirs = 0
files = 0
for root,dirs,files in os.walk("e:\testdemo"):
    os.chdir(root)
    for dir in dirs:
        if dir =="xxx":
            os.rmdir(dir)
    for file in files:
        if ".txt"  in file:
            os.remove(file)

方式2:
#encoding=utf-8
import os
import os.path

dir_count=0
file_count=0
for root, dirs, files in os.walk("e:\testdemo",topdown=True) :
    print(u"当前目录:",root) #打印目录绝对路径
    for name in files :
        print(u‘文件名:‘,os.path.join(root,name) )#打印文件绝对路径
        if name[-4:]==".txt":
            os.remove(os.path.join(root,name))
        file_count+=1
    for name in dirs :
        print(u‘目录名:‘,name) #打印目录绝对路径
        if name =="xxx":
            os.rmdir(os.path.join(root,name))
        dir_count+=1

print ("目录个数%s" %dir_count)
print ("文件个数%s" %file_count)

习题7:统计一个文件夹下所有文件类型            
#encoding =utf-8
import os

result = []
for root,dirs,files in os.walk("e:\python\python2"):
    os.chdir(root)
    for file in files:
        post_name = os.path.splitext(file)[1]
        if post_name != "":
            result.append(post_name)

print(list(set(result)))
print(len(list(set(result))))   

以上是关于python学习23_目录习题的主要内容,如果未能解决你的问题,请参考以下文章

Python__函数习题

分享《自然语言处理理论与实战》PDF及代码+唐聃+《深入浅出Python机器学习》PDF及代码+段小手+《深度学习实践:计算机视觉》PDF+缪鹏+《最优化理论与算法第2版》高清PDF+习题解答PDF+

商品房数据统计Python习题(保姆级图文+实现代码)

Python学习16 正则表达式3 练习题

python3----练习题(爬取电影天堂资源)

python小知识片段