1. 程式人生 > >python學習23_目錄習題

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次\n" %(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))))