PYTHON 文件操作之创建,删除,修改处理

 

平时会对一些对系统文件或者目录的进行增删改查,这就需要用到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)

时间: 2024-07-31 10:05:56

PYTHON 文件操作之创建,删除,修改处理的相关文章

python 文件操作api(文件操作函数)_python

python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove() 删除多个目录:os.removedirs(r"c:\python") 检验给出的路径是否是一个文件:os.path.isfile() 检验给出的路径是否是一个目录:os.path.isdir() 判断是否是绝对路

Python文件操作类操作实例详解_python

本文讲述了Python文件操作类的操作实例,详细代码如下: #!/usr/bin/env python #!/usr/bin/env python #coding:utf-8 # Purpose: 文件操作类 #声明一个字符串文本 poem=''' Programming is fun测试 When the work is done if you wanna make your work also fun: use Python! ''' #创建一个file类的实例,模式可以为:只读模式('r'

python 文件操作

python文件操作 #判断文件是否存在 os.path.exists(src_dir) #文件拷贝 open(des_file_name, "wb").write(open(src_file_name, "rb").read()) #文件重命名 os.rename(old_name, new_name) #列出指定目录下的所有文件名称 os.listdir(path_name) #删除单个文件 os.remove() # 删除空文件 os.rmdir() # 删除

python文件操作之目录遍历实例分析

  本文实例讲述了python文件操作之目录遍历的方法.分享给大家供大家参考.具体分析如下: Python的os模块,包含了普遍的操作系统功能,这里主要学习与路径相关的函数: os.listdir(dirname):列出dirname下的目录和文件 os.getcwd():获得当前工作目录 os.curdir:返回当前目录('.') os.chdir(dirname):改变工作目录到dirname os.path.isdir(name):判断name是不是一个目录,name不是目录就返回fals

关于python文件操作

总是记不住API.昨晚写的时候用到了这些,但是没记住,于是就索性整理一下吧: python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove() 删除多个目录:os.removedirs(r"c:\python") 检验给出的路径是否是一个文件:os.path.isfile()

第十二章 Python文件操作

12.1 open() open()函数作用是打开文件,返回一个文件对象. 用法格式:open(name[, mode[, buffering[,encoding]]]) -> file object name 文件名 mode 模式,比如以只读方式打开 buffering 缓冲区 encoding 返回数据采用的什么编码,一般utf8或gbk Mode Description r 只读,默认 w 只写,打开前清空文件内容 a 追加 a+ 读写,写到文件末尾 w+ 可读写,清空文件内容 r+ 可

python文件操作整理汇总_python

总是记不住API.昨晚写的时候用到了这些,但是没记住,于是就索性整理一下吧: python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove() 删除多个目录:os.removedirs(r"c:\python") 检验给出的路径是否是一个文件:os.path.isfile()

Python文件操作函数详解

相关的API: 文件夹: 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove() 删除多个目录:os.removedirs(r"c:python") 检验给出的路径是否是一个文件:os.path.isfile() 检验给出的路径是否是一个目录:os.path.isdir() 判断是否是绝对路径:os.path.isabs() 检验给出的路径是否真地存:os

Python文件操作类操作实例代码

  #!/usr/bin/env python 01 #!/usr/bin/env python  02 #coding:utf-8  03 # Author: 酷酷 04 # Purpose: 文件操作类  05 # Created: 2011/1/1  06  07 #声明一个字符串文本  08 poem='''  09 Programming is fun测试  10 When the work is done  11 if you wanna make your work also fu