99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python 操作文件的基本方法總結
Python 操作文件的基本方法總結
2017-09-15
收藏

Python 操作文件的基本方法總結

這篇文章主要介紹了Python 操作文件的基本方法總結的相關資料,這里說明了九種操作文件的方法,并附上實現(xiàn)方法,

Python 操作文件

編程語言對文件系統(tǒng)的操作是一項必不可少的功能,各種編程語言基本上都有對文件系統(tǒng)的操作,最簡潔的莫過于linux里面shell的操作了,其次,則是python,ruby等動態(tài)語言的操作,那么,今天散仙來看下,在python里面如何使用一些常用的操作文件功能。
主要包括:
1,創(chuàng)建一個文件
2,刪除一個文件
3,創(chuàng)建一個目錄
4,刪除一個目錄
5,拷貝,重命名,查看文件大小
6,列出某個目錄下文件的數(shù)量
7,遞歸打印某個目錄下的所有文件和目錄
8,讀寫文件操作
9,剪切,或者拷貝整個目錄或文件到另一個位置下

1,創(chuàng)建文件方法:    
f=open("D://111.cc",mode="w",encoding="UTF-8")
f.close()

2,刪除一個文件    
import os
os.remove("D://222.ccc123")
os.close()

3,創(chuàng)建一個目錄或多個目錄    
os.mkdir("E://bb")
os.makedirs("D:\\a\\b")

4,刪除依舊用remove方法或多級刪除    
os.removedirs(path)
os.remove()

5,拷貝,重命名,查看文件大小    
import os
import shutil
#第一個參數(shù)是源文件,第二個拷貝文件
shutil.copyfile("D://111.CC","D://222.ccc")
os.rename("D://222.ccc","D://222.ccc123")
os.stat("D://abc.txt").st_size

6,查看某個目錄下文件數(shù)量:
    
def countDirs(dp):
  tt=tuple(os.walk(dp))
  print("文件夾"+dp+"的信息:")
  print("文件夾的個數(shù): ",len(tt[0][1]),"文件的個數(shù): ",len(tt[0][2]))
 
d1="D:\\tomcat7\\bin"
countDirs(d1)

結果如下:    
文件夾D:\tomcat7\bin的信息:
文件夾的個數(shù): 0 文件的個數(shù): 28
 
Process finished with exit code 0

7,遞歸打印文件夾的方法:    
def showAllDirs(dp):
 
  tt=os.walk(dp);
  for l in tt:
    for lf in l[1]:
      print("目錄的路徑是:",l[0]+"\\"+lf)

遞歸打印文件的方法:    
def showAllDirsFiles(dirPath):
    tt=os.walk(dirPath);
    for l in tt:
      for ll in l[2]:
         print("文件的路徑是:",l[0]+"\\"+ll)

8,讀取文件的方法:    
def readFile():
  f=open(r"D:///bbb.txt",encoding="UTF-8")
  for line in f:
    #去除多余的換行符
    print(line.strip())
  f.close();

批量載入讀?。?br />     
def readFile1():
  f=open(r"D:///bbb.txt",encoding="UTF-8")
  while 1:
    #print("j")
    lines=f.readlines(10000);
    if not lines:
      #print("end")
      break;
    for line in lines:
      print(line.strip())
 
  f.close()

寫入文件例子:
    
def writeFile():
  a=list();
  a.append("a你好")
  a.append("b哈嘍")
  a.append("c")
  #a追加模式w覆蓋模式
  f=open("D://pp.txt",mode='a',encoding="UTF-8")
  print("文件大小:",f)
 
  for c in a:
    f.write(c+"\n")
  f.close()
  print("寫入成功!")
最后需要注意一點,注意路徑的寫法需要使用\\兩個符號加轉義實現(xiàn),如果只寫一個,可能會導致問題!
9,拷貝,或剪切的例子
#拷貝整個目錄到另一個路徑下
shutil.copytree("E:\\11111111111\\a","E:\\11111111111\\b");
#剪切整個目錄到另一個路徑下
shutil.move("E:\\11111111111\\a","E:\\11111111111\\cc")
以上就是python操作文件方法的總結

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師考試動態(tài)
數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調,回調的第一個參數(shù)驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }