新聞中心
Python中怎么實(shí)現(xiàn)簡(jiǎn)單文件操作,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
創(chuàng)新互聯(lián)是一家成都網(wǎng)站制作、成都做網(wǎng)站,提供網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站設(shè)計(jì),網(wǎng)站制作,建網(wǎng)站,按需求定制網(wǎng)站,網(wǎng)站開(kāi)發(fā)公司,從2013年開(kāi)始是互聯(lián)行業(yè)建設(shè)者,服務(wù)者。以提升客戶品牌價(jià)值為核心業(yè)務(wù),全程參與項(xiàng)目的網(wǎng)站策劃設(shè)計(jì)制作,前端開(kāi)發(fā),后臺(tái)程序制作以及后期項(xiàng)目運(yùn)營(yíng)并提出專業(yè)建議和思路。
現(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()
來(lái)讀取文件內(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()
關(guān)于Python中怎么實(shí)現(xiàn)簡(jiǎn)單文件操作問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
網(wǎng)站名稱:Python中怎么實(shí)現(xiàn)簡(jiǎn)單文件操作
網(wǎng)站鏈接:http://www.ef60e0e.cn/article/josigg.html