python_basic2

pyhton基礎知識 two

數據結構

  • 列表
  • 元組
  • 字典

列表

list = ['apple', 'mango', 'carrot', 'banana']

len(list)

list.append(’ ‘)

list.sort()

del list[0]

print 'These items are:', # Notice the comma at end of the line

我們在print語句的結尾使用了一個逗號來消除每個print語句自動打印的換行符。

元組

tuple = ('wolf', 'elephant', 'penguin')
tuple2 = ('wolf', 'elephant', tuple)
print tuple2
print tuple2[2]
print  tuple2[2][2]

輸出

('wolf', 'elephant', ('wolf', 'elephant', 'penguin'))
('wolf', 'elephant', 'penguin')
penguin

含有0個或1個項目的元組。一個空的元組由一對空的圓括號組成,如myempty = ()。然而,含有單個元素的元組就不那麼簡單了。你必須在第一個(唯一一個)項目後跟一個逗號,這樣Python才能區分元組和表達式中一個帶圓括號的對象。即如果你想要的是一個包含項目2的元組的時候,你應該指明singleton = (2 , )

print打印

age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name

字典

dict = {key1 : value1, key2 : value2 }

特點:

  • key唯一
  • 字典中的鍵/值對是沒有順序
ab = { 'Swaroop' : '[email protected]',
'Larry' : '[email protected]',
'Matsumoto' : '[email protected]'
}
print "Swaroop's address is %s" % ab['Swaroop']
# Adding a key/value pair
ab['Guido'] = '[email protected]'
# Deleting a key/value pair
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
    print 'Contact %s at %s' % (name, address)
if 'Guido' in ab: # OR ab.has_key('Guido')  #in操作符來檢驗一個鍵/值對是否存在,或者使用dict類的has_key方法
    print "\nGuido's address is %s" % ab['Guido']

引用

shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist

輸出:

shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana'] #因爲mylist和shoplist指向同一個地址
mylist = shoplist[:]   # 切片操作符來取得拷貝
del mylist[0] # remove first item
print 'shoplist is', shoplist
print 'mylist is', mylist

輸出:

shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

如果你只是想要使用另一個變量名,兩個名稱都 引用 同一個對象,那麼如果你不小心的話,可能會引來各種麻煩

str

name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"'

if 'a' in name:
print 'Yes, it contains the string "a"'

if name.find('war') != -1:   #  find函數返回值:如果查到:返回查找的第一個出現的位置。否則,返回-1。
print 'Yes, it contains the string "war"'

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)    #   Brazil_*_Russia_*_India_*_China

startwith方法是用來測試字符串是否以給定字符串開始。

in操作符用來檢驗一個給定字符串是否爲另一個字符串的一部分。

find 方法用來找出給定字符串在另一個字符串中的位置,或者返回-1以表示找不到子字符串。

str類也有以一個作爲分隔符的字符串join序列的項目的整潔的方法,它返回一個生成的大字符串。

python腳本

Q:我想要一個可以爲我的所有重要文件創建備份的程序。

solution:

  1. 需要備份的文件和目錄由一個列表指定。
  2. 備份應該保存在主備份目錄中。
  3. 文件備份成一個zip文件。
  4. zip存檔的名稱是當前的日期和時間。
  5. 我們使用標準的zip命令,它通常默認地隨Linux/Unix發行版提供。Windows用戶可以使
    用Info-Zip程序。注意你可以使用任何地存檔命令,只要它有命令行界面就可以了,那
    樣的話我們可以從我們的腳本中傳遞參數給它。
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'

你可以把source列表和target目錄設置成任何文件和目錄名,但是在Windows中你得小心一些。問題是Windows把反斜槓(\)作爲目錄分隔符,而Python用反斜槓表示轉義符!所以,你得使用轉義符來表示反斜槓本身或者使用自然字符串。例如,使用’C:\\Documents’或r’C:\Documents’而不是’C:\Documents’——你在使用一個不知名的轉義符\D!

我的win10使用的是好壓,我在好壓的根目錄中找到用命令行操作好壓進行壓縮HaoZipC

不要在IDE中運行該腳本,不然會出現IDE找不到命令的問題,在cmd中 python 文件.py運行該腳本即可

改版

#!usr/bin/python    
#Filename:backup_ver1.py


import os
import time
source=['D:\\test_backup','d:\\teleport_ultra']
#on windows  source=[r'D:\test_backup',r'd:\teleport_ultra']
target_dir='D:\\backup\\'

today = target_dir + time.strftime('%Y%m%d')

now = time.strftime('%H%M%S')

comment = raw_input('Enter a comment --> ')  #獲取輸入付給comment

if len(comment) == 0:               # check if a comment was entered
    target_name = today + os.sep + now + '.zip'
else:
    target_name = today + os.sep + now + '_' +\  #用斜槓來連接下一行代碼
    comment.replace(' ', '_') + '.zip'    #字符串替換將空格替換爲下劃線

if not os.path.exists(today):   #檢查目錄是否存在
    os.mkdir(today)         # make directory  創建目錄
    print 'Successfully created directory', today


zip_command="HaoZipC a -tzip %s %s"%(target_name,' '.join(source))  #' '.join(source)以空格連接字符串

if os.system(zip_command)==0:
    print 'Successful backup to',target_name
else:
    print 'Backup fail'

os.path.exists() 文件夾是否存在

os.mkdir()創建文件夾

os.sep變量的用法——這會根據你的操作系統給出目錄分隔符,即在Linux、Unix下它是’/’,在Windows下它是’\’,而在Mac OS下它是’:’。使用os.sep而非直接使用字符,會使我們的程序具有移植性,可以在上述這些系統下工作。

進一步優化

你可以在程序中包含 交互 程度——你可以用-v選項來使你的程序更具交互性。

另一個可能的改進是使文件和目錄能夠通過命令行直接傳遞給腳本。我們可以通過sys.argv列表來獲取它們,然後我們可以使用list類提供的extend方法把它們加到source列表中去。

我還希望有的一個優化是使用tar命令替代zip命令。這樣做的一個優勢是在你結合使用tar和gzip命令的時候,備份會更快更小。如果你想要在Windows中使用這些歸檔,WinZip也能方便地處理這些.tar.gz文件。tar命令在大多數Linux/Unix系統中都是默認可用的。Windows用戶也可以下載安裝它。命令字符串現在將稱爲:

tar = 'tar -cvzf %s %s -X /home/swaroop/excludes.txt' % (target, ' '.join(srcdir))

選項解釋如下:
● -c表示創建一個歸檔。
● -v表示交互,即命令更具交互性。
● -z表示使用gzip濾波器。
● -f表示強迫創建歸檔,即如果已經有一個同名文件,它會被替換。
● -X表示含在指定文件名列表中的文件會被排除在備份之外。例如,你可以在文件中指定*~,從而不讓備份包括所有以~結尾的文件。
重要
最理想的創建這些歸檔的方法是分別使用zipfile和tarfile。它們是Python標準庫的一部分,可以供你使用。使用這些庫就避免了使用os.system這個不推薦使用的函數,它容易引發嚴重的錯誤。

the byte of python notes

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章