python zipfile 把整個文件夾內的文件打包 沒有生成.zip文件

- 如果操作系統為 Windows 7 請先 "以管理員身份運行" cmd.exe

cmd.exe 在 C:WindowsSystem32 文件夾下。


#!/usr/bin/python
#coding:utf-8
importos
importsys
importzipfile

path='e:\pythonWorkSpace\practice'
zipfilename='e:\version.zip'

#pathisadireactoryornot.
ifnotos.path.isdir(path):
printpath+'Nosuchadireactory'
exit()

ifos.path.exists(zipfilename):
#zipfilenameisexist.Append.
print'Addfilesinto'+zipfilename
zipfp=zipfile.ZipFile(zipfilename,'a',zipfile.ZIP_DEFLATED)
fordirpath,dirnames,filenamesinos.walk(path,True):
forfilanameinfilenames:
direactory=os.path.join(dirpath,filaname)
print'Add...'+direactory
zipfp.write(direactory)
else:
#zipfilenameisnotexist.Create.
print'Createnewfile'+zipfilename
zipfp=zipfile.ZipFile(zipfilename,'w',zipfile.ZIP_DEFLATED)
fordirpath,dirnames,filenamesinos.walk(path,True):
forfilanameinfilenames:
direactory=os.path.join(dirpath,filaname)
print'Compress...'+direactory
zipfp.write(direactory)
#.
zipfp.close()

② 在cmd中運行python程序報錯no such file or direactory

-
如果操作系統為
Windows
7
請先
"以管理員身份運行"
cmd.exe
cmd.exe

C:\Windows\System32
文件夾下。
-
先試試:
dir
Python文件全路徑名
如:
dir
E:\pythonWorkSpace\all.py
看看是否存在文件
'all.py'。
如果文件存在
-
再試試:
Python2.7.5可執行文件全路徑名
Python文件全路徑名
如:
C:\Python27\python.exe
E:\pythonWorkSpace\all.py

③ python 每隔一秒循環發10條數據 為什麼是10條一起發出去的

importtime
fromtwisted.internetimportprotocol,reactor,defer,threads
classEcho(protocol.Protocol):
defconnectionMade(self):
#1.writeSomeData
defwriteSomeData():
i=10
whilei:
self.transport.writeSomeData(time.strftime('%H:%M:%S',time.localtime(time.time())))
self.transport.writeSomeData(' ')
time.sleep(2)
i-=1
writeSomeData()
#2,threads.deferToThread
defwrite():
i=10
whilei:
self.transport.write(time.strftime('%H:%M:%S',time.localtime(time.time())))
self.transport.write(' ')
time.sleep(2)
i-=1
threads.deferToThread(write)

classEchoFactory(protocol.Factory):
defbuildProtocol(self,addr):
returnEcho()

reactor.listenTCP(8000,EchoFactory())
reactor.run()

寫了兩種方法writeSomeData,deferToThread

④ 這個提示是不是twisted框架沒有安裝好

要下一個zope.interface裝,google一下網上有

⑤ Python核心編程的圖書目錄

第1部分Python核心
第1章歡迎來到Python世界
第2章快速入門
第3章Python基礎
第4章Python對象
第5章數字
第6章序列:字元串、列表和元組
第7章映像和集合類型
第8章條件和循環
第9章文件和輸入輸出
第10章錯誤和異常
第11章函數和函數式編程
第12章模塊
第13章面向對象編程
第14章執行環境
第2部分高級主題
第15章正則表達式
15.1引言/動機
15.2正則表達式使用的特殊符號和字元
15.2.1用管道符號(|)匹配多個正則表達式模式
15.2.2匹配任意一個單個的字元(.)
15.2.3從字元串的開頭或結尾或單詞邊界開始匹配(^/$ / /B )
15.2.4創建字元類([])
15.2.5指定范圍(-)和否定(^)
15.2.6使用閉包操作符(*,+,?,{})實現多次出現/重復匹配
15.2.7特殊字元表示、字元集
15.2.8用圓括弧(())組建組
15.3正則表達式和Python語言
15.3.1re模塊:核心函數和方法
15.3.2使用compile()編譯正則表達式
15.3.3匹配對象和group()、groups()方法
15.3.4用match()匹配字元串
15.3.5search()在一個字元串中查找一個模式(搜索與匹配的比較)
15.3.6匹配多個字元串(|)
15.3.7匹配任意單個字元(.)
15.3.8創建字元集合([])
15.3.9重復、特殊字元和子組
15.3.10從字元串的開頭或結尾匹配及在單詞邊界上的匹配
15.3.11用findall()找到每個出現的匹配部分
15.3.12用sub()(和subn())進行搜索和替換
15.3.13用split()分割(分隔模式)
15.4正則表達式示例
15.4.1匹配一個字元串
15.4.2搜索與匹配的比較,「貪婪」匹配
15.5練習
第16章網路編程
16.1引言
16.1.1什麼是客戶端/伺服器架構
16.1.2客戶端/伺服器網路編程
16.2套接字:通信端點
16.2.1什麼是套接字
16.2.2套接字地址:主機與埠
16.2.3面向連接與無連接
16.3Python中的網路編程
16.3.1socket()模塊函數
16.3.2套接字對象(內建)方法
16.3.3創建一個TCP伺服器
16.3.4創建TCP客戶端
16.3.5運行我們的客戶端與TCP伺服器
16.3.6創建一個UDP伺服器
16.3.7創建一個UDP客戶端
16.3.8執行UDP伺服器和客戶端
16.3.9Socket模塊屬性
16.4*SocketServer模塊
16.4.1創建一個SocketServerTCP伺服器
16.4.2創建SocketServerTCP客戶端
16.4.3執行TCP伺服器和客戶端
16.5Twisted框架介紹
16.5.1創建一個Twisted Reactor TCP伺服器
16.5.2創建一個Twisted Reactor TCP客戶端
16.5.3執行TCP伺服器和客戶端
16.6相關模塊
16.7練習
第17章網路客戶端編程
17.1什麼是網際網路客戶端
17.2文件傳輸
17.2.1文件傳輸網際協議
17.2.2文件傳輸協議(FTP)
17.2.3Python和FTP
17.2.4ftplib.FTP類方法
17.2.5互動式FTP示例
17.2.6客戶端FTP程序舉例
17.2.7FTP的其他方面
17.3網路新聞
17.3.1Usenet與新聞組
17.3.2網路新聞傳輸協議(NNTP)
17.3.3Python和NNTP
17.3.4nntplib.NNTP類方法
17.3.5互動式NNTP舉例
17.3.6客戶端程序NNTP舉例
17.3.7NNTP的其他方面
17.4電子郵件
17.4.1電子郵件系統組件和協議
17.4.2發送電子郵件
17.4.3Python和SMTP
17.4.4smtplib.SMTP類方法
17.4.5互動式SMTP示例
17.4.6SMTP的其他方面
17.4.7接收電子郵件
17.4.8POP和IMAP
17.4.9Python和POP3
17.4.10互動式POP3舉例
17.4.11poplib.POP3類方法
17.4.12客戶端程序SMTP和POP3舉例
17.5相關模塊
17.5.1電子郵件
17.5.2其他網路協議
17.6練習
第18章多線程編程
18.1引言/動機
18.2線程和進程
18.2.1什麼是進程
18.2.2什麼是線程
18.3Python、線程和全局解釋器鎖
18.3.1全局解釋器鎖(GIL)
18.3.2退出線程
18.3.3在Python中使用線程
18.3.4沒有線程支持的情況
18.3.5Python的threading模塊
18.4thread模塊
18.5threading模塊
18.5.1Thread類
18.5.2斐波那契、階乘和累加和
18.5.3threading模塊中的其他函數
18.5.4生產者-消費者問題和Queue模塊
18.6相關模塊
18.7練習
第19章圖形用戶界面編程
19.1簡介
19.1.1什麼是Tcl、Tk和Tkinter
19.1.2安裝和使用Tkinter533
19.1.3客戶端/伺服器架構534
19.2Tkinter與Python編程534
19.2.1Tkinter模塊:把Tk引入你的程序
19.2.2GUI程序開發簡介
19.2.3頂層窗口:
19.2.4Tk組件
19.3Tkinter舉例
19.3.1標簽組件
19.3.2按鈕組件
19.3.3標簽和按鈕組件
19.3.4標簽、按鈕和進度條組件
19.3.5偏函數應用舉例
19.3.6中級Tkinter範例
19.4其他GUI簡介
19.4.1Tk Interface eXtensions (Tix)
19.4.2Python MegaWidgets (PMW)
19.4.3wxWidgets和wxPython
19.4.4GTK+和PyGTK
19.5相關模塊和其他GUI
19.6練習
第20章Web編程
20.1介紹
20.1.1Web應用:客戶端/伺服器計算
20.1.2網際網路
20.2使用Python進行Web應用:創建一個簡單的Web客戶端
20.2.1統一資源定位符
20.2.2urlparse模塊
20.2.3urllib模塊
20.2.4urllib2模塊
20.3高級Web客戶端
20.4CGI:幫助Web伺服器處理客戶端數據
20.4.1CGI介紹
20.4.2CGI應用程序
20.4.3cgi模塊
20.5建立CGI應用程序
20.5.1建立Web伺服器
20.5.2建立表單頁
20.5.3生成結果頁
20.5.4生成表單和結果頁面
20.5.5全面交互的Web站點
20.6在CGI中使用Unicode編碼
20.7高級CGI
20.7.1Mulitipart表單提交和文件的上傳
20.7.2多值欄位
20.7.3cookie
20.7.4使用高級CGI
20.8Web(HTTP)伺服器
20.9相關模塊
20.10練習
第21章資料庫編程
21.1介紹
21.1.1持久存儲
21.1.2基本的資料庫操作和SQL語言
21.1.3資料庫和Python
21.2Python資料庫應用程序程序員介面(DB-API)
21.2.1模塊屬性
21.2.2連接對象
21.2.3游標對象
21.2.4類型對象和構造器
21.2.5關系資料庫
21.2.6資料庫和Python:介面程序
21.2.7使用資料庫介面程序舉例
21.3對象-關系管理器(ORM)
21.3.1考慮對象,而不是SQL
21.3.2Python和ORM
21.3.3雇員資料庫舉例
21.3.4總結
21.4相關模塊
21.5練習
第22章擴展Python623
22.1引言/動機
22.1.1什麼是擴展
22.1.2為什麼要擴展Python
22.2創建Python擴展
22.2.1創建您的應用程序代碼
22.2.2用樣板來包裝你的代碼
22.2.3編譯
22.2.4導入和測試
22.2.5引用計數
22.2.6線程和全局解釋器鎖(GIL)
22.3相關話題
22.4練習
第23章其他話題
23.1Web服務
23.2用Win32的COM來操作微軟Office
23.2.1客戶端COM編程
23.2.2 微軟Excel
23.2.3微軟Word第1部分Python核心
23.2.4微軟PowerPoint
23.2.5微軟Outlook
23.2.6中等規模的例子
23.3用Jython寫Python和Java的程序
23.3.1什麼是Jython
23.4練習
23.2.4微軟PowerPoint
23.2.5微軟Outlook
23.2.6中等規模的例子
23.3用Jython寫Python和Java的程序
23.3.1什麼是Jython
23.3.2Swing GUI開發(Java或者Python!)
23.4練習

⑥ Python安裝Scrapy出現以下錯誤怎麼辦

itcast@itcast:~/pachong$ scrapy
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 7, in <mole>
from scrapy.cmdline import execute
File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 9, in <mole>
from scrapy.crawler import CrawlerProcess
File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 6, in <mole>
from twisted.internet import reactor, defer
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/reactor.py", line 38, in <mole>
from twisted.internet import default
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/default.py", line 56, in <mole>
install = _getInstallFunction(platform)
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/default.py", line 44, in _getInstallFunction
from twisted.internet.epollreactor import install
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/epollreactor.py", line 24, in <mole>
from twisted.internet import posixbase
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 18, in <mole>
from twisted.internet import error, udp, tcp
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 28, in <mole>
from twisted.internet._newtls import (
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/_newtls.py", line 21, in <mole>
from twisted.protocols.tls import TLSMemoryBIOFactory, TLSMemoryBIOProtocol
File "/usr/local/lib/python2.7/dist-packages/twisted/protocols/tls.py", line 63, in <mole>
from twisted.internet._sslverify import _setAcceptableProtocols
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/_sslverify.py", line 38, in <mole>
TLSVersion.TLSv1_1: SSL.OP_NO_TLSv1_1,
AttributeError: 'mole' object has no attribute 'OP_NO_TLSv1_1'

⑦ 在cmd中運行python程序報錯no such file or direactory

- 如果操作系統為 Windows 7 請先 "以管理員身份運行" cmd.exe
cmd.exe 在 C:\Windows\System32 文件夾下。

- 先試試:
dir Python文件全路徑名
如:
dir E:\pythonWorkSpace\all.py
看看是否存在文件 'all.py'。

如果文件存在
- 再試試:
Python2.7.5可執行文件全路徑名 Python文件全路徑名
如:
C:\Python27\python.exe E:\pythonWorkSpace\all.py

⑧ python的計時器

你可以用Twisted來實現,源代碼如下:

from twisted.internet import task
from twisted.internet import reactor

#set global variables
g = 0
def run():
global g
g = g + 1
print 'the global value g is:%s'%g
#add function run to twisted's looping call
l = task.LoopingCall(run)
#set interval to 5*60 seconds
l.start(5*60)
reactor.run()
要運行這段代碼你得裝twisted和zope中關於interface的定義,上google搜搜載一個裝了就可以了。

⑨ python打包工具 生成文件在哪

如果操作系統為 Windows 7 請先 "以管理員身份運行" cmd.exe
cmd.exe 在 C:\Windows\System32 文件夾下。

#! /usr/bin/python
#coding: utf-8
import os
import sys
import zipfile

path = 'e:\\pythonWorkSpace\\practice'
zipfilename = 'e:\\version.zip'

# path is a direactory or not.
if not os.path.isdir(path):
print path + ' No such a direactory'
exit()

if os.path.exists(zipfilename):
# zipfilename is exist.Append.
print 'Add files into ' + zipfilename
zipfp = zipfile.ZipFile(zipfilename, 'a' ,zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(path, True):
for filaname in filenames:
direactory = os.path.join(dirpath,filaname)
print 'Add... ' + direactory
zipfp.write(direactory)
else:
# zipfilename is not exist.Create.
print 'Create new file ' + zipfilename
zipfp = zipfile.ZipFile(zipfilename, 'w' ,zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(path, True):
for filaname in filenames:
direactory = os.path.join(dirpath,filaname)
print 'Compress... ' + direactory
zipfp.write(direactory)
# Flush and Close zipfilename at last.
zipfp.close()

⑩ 如何使用python爬蟲jfinal

一、gzip/deflate支持

現在的網頁普遍支持gzip壓縮,這往往可以解決大量傳輸時間,以VeryCD的主頁為例,未壓縮版本247K,壓縮了以後45K,為原來的1/5。這就意味著抓取速度會快5倍。

然而python的urllib/urllib2默認都不支持壓縮,要返回壓縮格式,必須在request的header裡面寫明』accept-
encoding』,然後讀取response後更要檢查header查看是否有』content-encoding』一項來判斷是否需要解碼,很繁瑣瑣
碎。如何讓urllib2自動支持gzip, defalte呢?

其實可以繼承BaseHanlder類,然後build_opener的方式來處理:

import urllib2
from gzip import GzipFile
from StringIO import StringIO
class ContentEncodingProcessor(urllib2.BaseHandler):
"""A handler to add gzip capabilities to urllib2 requests """

# add headers to requests
def http_request(self, req):
req.add_header("Accept-Encoding", "gzip, deflate")
return req

# decode
def http_response(self, req, resp):
old_resp = resp
# gzip
if resp.headers.get("content-encoding") == "gzip":
gz = GzipFile(
fileobj=StringIO(resp.read()),
mode="r"
)
resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
resp.msg = old_resp.msg
# deflate
if resp.headers.get("content-encoding") == "deflate":
gz = StringIO( deflate(resp.read()) )
resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code) # 'class to add info() and
resp.msg = old_resp.msg
return resp

# deflate support
import zlib
def deflate(data): # zlib only provides the zlib compress format,not the deflate format;
try: # so on top of all there's this workaround:
return zlib.decompress(data, -zlib.MAX_WBITS)
except zlib.error:
return zlib.decompress(data)

然後就簡單了,

encoding_support = ContentEncodingProcessor
opener = urllib2.build_opener( encoding_support, urllib2.HTTPHandler )

#直接用opener打開網頁,如果伺服器支持gzip/defalte則自動解壓縮
content = opener.open(url).read()

二、更方便地多線程

總結一文的確提及了一個簡單的多線程模板,但是那個東東真正應用到程序裡面去只會讓程序變得支離破碎,不堪入目。在怎麼更方便地進行多線程方面我也動了一番腦筋。先想想怎麼進行多線程調用最方便呢?

1、用twisted進行非同步I/O抓取

事實上更高效的抓取並非一定要用多線程,也可以使用非同步I/O法:直接用twisted的getPage方法,然後分別加上非同步I/O結束時的callback和errback方法即可。例如可以這么干:

from twisted.web.client import getPage
from twisted.internet import reactor

links = [ 'http://www.verycd.com/topics/%d/'%i for i in range(5420,5430) ]

def parse_page(data,url):
print len(data),url

def fetch_error(error,url):
print error.getErrorMessage(),url

# 批量抓取鏈接
for url in links:
getPage(url,timeout=5)
.addCallback(parse_page,url) #成功則調用parse_page方法
.addErrback(fetch_error,url) #失敗則調用fetch_error方法

reactor.callLater(5, reactor.stop) #5秒鍾後通知reactor結束程序
reactor.run()

twisted人如其名,寫的代碼實在是太扭曲了,非正常人所能接受,雖然這個簡單的例子看上去還好;每次寫twisted的程序整個人都扭曲了,累得不得了,文檔等於沒有,必須得看源碼才知道怎麼整,唉不提了。

如果要支持gzip/deflate,甚至做一些登陸的擴展,就得為twisted寫個新的HTTPClientFactory類諸如此類,我這眉頭真是大皺,遂放棄。有毅力者請自行嘗試。

這篇講怎麼用twisted來進行批量網址處理的文章不錯,由淺入深,深入淺出,可以一看。

2、設計一個簡單的多線程抓取類

還是覺得在urllib之類python「本土」的東東裡面折騰起來更舒服。試想一下,如果有個Fetcher類,你可以這么調用

f = Fetcher(threads=10) #設定下載線程數為10
for url in urls:
f.push(url) #把所有url推入下載隊列
while f.taskleft(): #若還有未完成下載的線程
content = f.pop() #從下載完成隊列中取出結果
do_with(content) # 處理content內容

這么個多線程調用簡單明了,那麼就這么設計吧,首先要有兩個隊列,用Queue搞定,多線程的基本架構也和「技巧總結」一文類似,push方法和
pop方法都比較好處理,都是直接用Queue的方法,taskleft則是如果有「正在運行的任務」或者」隊列中的任務」則為是,也好辦,於是代碼如
下:

import urllib2
from threading import Thread,Lock
from Queue import Queue
import time

class Fetcher:
def __init__(self,threads):
self.opener = urllib2.build_opener(urllib2.HTTPHandler)
self.lock = Lock() #線程鎖
self.q_req = Queue() #任務隊列
self.q_ans = Queue() #完成隊列
self.threads = threads
for i in range(threads):
t = Thread(target=self.threadget)
t.setDaemon(True)
t.start()
self.running = 0

def __del__(self): #解構時需等待兩個隊列完成
time.sleep(0.5)
self.q_req.join()
self.q_ans.join()

def taskleft(self):
return self.q_req.qsize()+self.q_ans.qsize()+self.running

def push(self,req):
self.q_req.put(req)

def pop(self):
return self.q_ans.get()

def threadget(self):
while True:
req = self.q_req.get()
with self.lock: #要保證該操作的原子性,進入critical area
self.running += 1
try:
ans = self.opener.open(req).read()
except Exception, what:
ans = ''
print what
self.q_ans.put((req,ans))
with self.lock:
self.running -= 1
self.q_req.task_done()
time.sleep(0.1) # don't spam

if __name__ == "__main__":
links = [ 'http://www.verycd.com/topics/%d/'%i for i in range(5420,5430) ]
f = Fetcher(threads=10)
for url in links:
f.push(url)
while f.taskleft():
url,content = f.pop()
print url,len(content)