PYTHON 檔案操作之建立,刪除,修改處理

來源:互聯網
上載者:User

 

平時會對一些對系統檔案或者目錄的進行增刪改查,這就需要用到python的一些庫,例如os等

 


對檔案進行操作

首先要先引入os

Import os

讀寫一個檔案需要開啟這個檔案

可以用Open(dir,type)來操作,開啟一個檔案,或者寫一個檔案,中的目錄如果在windows中路徑需要用

”\” 雙斜杠分隔,也可以用r來保持字串中目錄原路徑r’c:/test.txt’

file = open(“c:\test.txt”,”w+”)  #開啟並對檔案進行寫操作

file = open(“c:\test.txt”,”r”)  #開啟並對檔案進行讀操作

 

刪除一個檔案可以用os.remove(dir,)

如果檔案為唯讀需要做一些其他的操作

引入stat

Import stat,os

os.chmod( filename, stat.S_IWRITE )

 

對一個目錄(檔案夾)進行操作

列出指定目錄下的檔案

import os

for filename in os.listdir(dir)

    #操作

 

判斷一個字串是不是一個目錄

利用os.isdir(dir)

 

遍曆一個目錄下的檔案可以用walk

for root,dirs,files in os.walk(rootdir)

    #

 
刪除一個檔案夾(裡邊可以有檔案)可以用:

先要包含一個shutil

import shutil

    shutil.rmtree(path)

上面一些基礎的檔案處理,下面我來介紹一個朋友寫的檔案建立,刪除,修改處理類。

#!/usr/bin/env python
#encoding:utf-8 # 支援中文輸入

import sys
import getpass
import shutil
import commands
import time
import fileinput

staff_list = 'contact_list.txt'

# 參數配置
user = 'admin'
passwd = '123456'
s = file(staff_list)
ss = s.readlines()
a = file(staff_list,'a')
counter = 0
_counter = 0

# 認證登陸
while True:
  # 計數器,超過3次強制退出
  if counter <= 3:
    # 空使用者名稱判斷
    name = raw_input("please input your name: ").strip()
    if len(name) == 0:
     print "empty name,try again!"
   continue

    # 使用者名稱密碼判斷,密碼隱藏
    # pwd =  raw_input("please input your password: ")
    pwd = getpass.getpass('please input your password:')
    if pwd == passwd and name == user:
   print "Welcome to login,%s" %name
    else:
   print "name or password is not valid,please try again!"
          counter +=1
   continue
    break
  else:
    print "exceeded 3 times user login..exit the script"
    sys.exit()

# 選擇增刪改查
while True:
  item = raw_input('''33[36;1mWelcome to login %s, what do you want to do?
-----------------------
press 'p' for print
press 'a' for add
press 'd' for delete
press 'u' for update
press 's' for select
press 'q' for quit
-----------------------
please make your choise: 33[0m''' % user)
 
  # 列印所有
  if item == 'p':
    while True:
      user_select = open(staff_list,'r')
      s_ = user_select.read()    
      print '                          '
      print '33[32;1mThe content of the file33[0m '
      print '33[32;1m--------------------------33[0m '
      print s_
      print '33[32;1m--------------------------33[0m '
      print '                          '
      break
   
  # 增加
  elif item == 'a':
    while True:
      user_add_num = raw_input(("33[32;1mplease input your number: 33[0m ").strip())
      user_add_name = raw_input(("33[32;1mplease input your name: 33[0m ").strip())
      user_add_dept = raw_input(("33[32;1mplease input your department: 33[0m ").strip

())
      user_add_id = raw_input(("33[32;1mplease input your id: 33[0m ").strip())
      user_item = '%st%st%st%s' %(user_add_num,user_add_name,user_add_dept,user_add_id)
      a.write("n%s" %user_item)
      a.flush()
      print "33[32;1mAdd item:33[0m"
      print "33[32;1m------------------33[0m"
      print user_item
      print "33[32;1m------------------33[0m"
      print "33[32;1mAdded successful!33[0m"
     
      # 刪除空行
      del_blank_in = open('contact_list.txt','r')
      del_blank_out = open('contact_list_new.txt','w')
      lines = del_blank_in.readlines()
      for blank in lines:
        if blank.split():
          del_blank_out.writelines(blank)
      del_blank_in.close()
      del_blank_out.close()
      # 覆蓋原檔案
      shutil.move('contact_list_new.txt','contact_list.txt')
      user_add_choise = raw_input('press Q for quit or press any key to continue: ')
      if user_add_choise == 'Q':
          print 'bye!'
          break
   
  # 刪除
  elif item == 'd':
    while True:
      user_del_input = raw_input("please input sth to delete: ").strip()
      if len(user_del_input) == 0:
        print "empty input,try again!"
      else:
        # 輸入值與源檔案比對,有則丟棄,沒有則添加到新檔案,最後新檔案覆蓋源檔案,實現刪除

功能
        with open('contact_list.txt','r') as ff:
          with open('contact_list.txt.new','w') as gg:
            for line in ff.readlines():
              if user_del_input not in line:
                gg.write(line)
       if user_del_input in line:
  print "33[32;1mDelete item:33[0m"
  print "33[32;1m------------------33[0m"
  print " %s " %line
  _counter += 1 # 計數器,判斷輸入值叫用次數
  print "33[32;1m------------------33[0m"
    print "33[32;1mDeleted successful!33[0m"
       if _counter == 0:
               print 'nothing delete!'
        shutil.move('contact_list.txt.new','contact_list.txt')
        # 退出刪除
        user_del_input_quit = raw_input("33[32;1mpress Q for quit or press any key to

continue? 33[0m").strip()
        if user_del_input_quit == 'Q':
            break     
 
 
  # 查詢
  elif item == 's':
    while True:
      match_yes = 0
      #輸入判斷,忽略空格輸入,加入顏色
      user_select_input = raw_input("33[32;1mplease input sth to search:33[0m ").strip

()
      contact_file = file (staff_list)
      if len(user_select_input) == 0:
        print "empty input,try again!"
      else:
        while True:
   line = contact_file.readline()
          if len(line) == 0:
       break
   if user_select_input in line:
       match_yes = 1
       print line
   else:
       pass
        if match_yes == 0 :
       print "No match item found"
      # 退出查詢
        user_select_input_quit = raw_input("33[32;1mpress Q for quit or press any key to

continue? 33[0m").strip()
        if user_select_input_quit == 'Q':
            break     
 
  # 修改
  elif item == 'u':
    while True:
      # 輸入為空白以及匹配查詢內容判斷
      user_update_input_from = raw_input("33[32;1mplease search sth to update: 33

[0m").strip()
      update_match = 0
      update_file = file(staff_list).readlines()
      for n_ in range(len(update_file)):
 if user_update_input_from in update_file[n_]:
     update_match = 1
 else:
     pass
      if update_match == 0:
       print "No match item found"
      elif len(user_update_input_from) == 0:
        print "empty input,try again!"
      else:
 # 將匹配到的字元修改為新字元
 while True:
     user_update_input_to = raw_input("33[32;1mupdate %s to what?33[0m " %

(user_update_input_from)).strip()
   if len(user_update_input_to) == 0:
            print "empty input,try again!"
   else:
       for line_ in fileinput.input(staff_list,inplace = 1,backup='.bak'):
         line_ = line_.replace(user_update_input_from,user_update_input_to)
         print line_
     # 列印修改字元的行
            print "33[32;1mupdate item:33[0m"
            output_ = commands.getoutput("diff contact_list.txt contact_list.txt.bak|grep

'^>.*' | sed 's/^>//g'")
     print "33[32;1m---------------------------33[0m"
            print output_
     print "33[32;1m---------------------------33[0m"
     print "33[32;1mupdate successfully!33[0m"
            # 刪除空行
            del_blank_in = open('contact_list.txt','r')
            del_blank_out = open('contact_list_new.txt','w')
            lines = del_blank_in.readlines()
            for blank in lines:
       if blank.split():
         del_blank_out.writelines(blank)
            del_blank_in.close()
            del_blank_out.close()
            # 覆蓋原檔案
            shutil.move('contact_list_new.txt','contact_list.txt')
     break
 # 退出更新
 user_update_input_quit = raw_input("33[32;1mpress Q for quit or press any key to

continue? 33[0m").strip()
        if user_update_input_quit == 'Q':
     break   
 
      
  # 退出
  elif item == 'q':
    print 'bye!'
    sys.exit()
 
  else:
    print "33[31;1mnot a valid key word33[0m"
    time.sleep(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.