Python文件操作簡(jiǎn)單示例剖析
在Python編程語(yǔ)言中,有很多比較有用的操作技巧值得我們?cè)趯W(xué)習(xí)和實(shí)踐中去熟練的掌握,以幫助我們應(yīng)用這一語(yǔ)言來實(shí)現(xiàn)各種功能。在這里我們就先來一起了解一下Python文件操作的相關(guān)應(yīng)用技巧。
現(xiàn)在以txt為例簡(jiǎn)單的講一下Python文件操作.
首先是建立關(guān)聯(lián)...假設(shè)在存在以下文件 e:test.txt
- This is line #1
- This is line #2
- This is line #3
- END
- >>> f = file('e:\test.txt', 'r')
關(guān)鍵字的***部分,是文件路徑及名稱。注意這里面,路徑需要用\
第二部分,是對(duì)文件的模式或者叫權(quán)限,一般有以下3種 "r" (read), "w" (write)和 "a"(append).
之后,就可以利用
- f_content = infile.read()
- f_content = infile.readlines()
來讀取文件內(nèi)容了
- >>> f = file('e:\test.txt', 'r')
- >>> ff_content = f.read()
- >>> print f_content
- This is line #1
- This is line #2
- This is line #3
- END
- >>> f.close()
- >>>
- >>> infile = file('e:\test.txt', 'r')
- >>> f = file('e:\test.txt', 'r')
- >>> for f_line in f.readlines():
- print 'Line:', f_line
- Line: This is line #1
- Line: This is line #2
- Line: This is line #3
- Line: END
- >>> f.close()
- >>>
然后是文件的寫入
- >>> f=file('e:\test.txt','w')
- >>> f.write('billrice')
- >>> f.write('testtest')
- >>> f.write('entern')
- >>> f.writelines(['billrice','ricerice'])
- >>> f.close()
- >>>
- >>> f=file('e:\test.txt','r')
- >>> content=f.read()
- >>> print content
- billricetesttestenter
- billricericerice
- >>>
在Python文件操作中,需要注意的是...在f.close()之前,c盤下面只有一個(gè)空空的test.txt,f.close()的作用相當(dāng)于***的存盤。
刪除文件:
- name='e:1.txt'
- os.remove(name)
壓縮文件:
- import os
- import zipfile
- import time
- # 壓縮目錄
- source_dir= r'F:web'
- # 按時(shí)間生成文件名稱
- target_file = time.strftime('%Y%m%d%H%M%S') + '.zip'
- myZipFile = zipfile.ZipFile(target_file, 'w' )# 壓縮所有文件,包含子目錄
- for root,dirs,files in os.walk(source_dir):
- for vfileName in files:
- fileName = os.path.join(root,vfileName)
- myZipFile.write( fileName, fileName, zipfile.ZIP_DEFLATED )
- # 壓縮完成
- myZipFile.close()
以上就是我們?yōu)榇蠹以敿?xì)介紹的Python文件操作的相關(guān)內(nèi)容。
【編輯推薦】