Python脚本语言 进阶篇(三)文件及目录操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yinshuilan/article/details/79544931
#脚本语言 - 文件操作
#1. 熟练掌握文件操作方法
#2. 练习:
    #1)读出指定文件内容
    #2)找到指定文件并往里添加/修改/删除内容


#coding=utf-8  
import random
import sys
import os, operator
import time
import logging


def readfile(infile):
    #读取指定文件内容
    '''f = open('test-easy.txt')
    text = f.read()
    for line in text.split('\n'):
        print(line)
    f.close()
    for line in f:
        print(line)
    f.close()'''
    try:
        with open(infile) as f:
            for line in f:
                print(line)
        f.close()
    except Exception as e:
        print("Error occurred:", e)


def createfile(newfile, startstr):
    #创建文件newfile,并写入startstr
    with open(newfile, 'w') as f:
        f.write(startstr)
    f.close()


def appendfile(file, x):
    #打开指定文件file, 追加内容x
    with open(file, 'a') as f:
        f.write(x)
    f.close()


def clearfile(file, size = 0):
    #从当前位置开始截断文件,size = 0即删除文件内容
    with open(file, 'w') as f: #'r+', 'rb+', 'w', 'wb', 'wb+'
        f.truncate(size)
    f.close()


def removefile(file):
    #删除文件
    try:
        os.remove(file)
    except Exception as e:
        print("Error occurred:", e)
   
def modifyFile(file,initStr,replaceStr):
    #找到指定文件将其中的initStr替换为replaceStr并保存
    found = 0
    checked = 0
    try:
        fr = open(file, 'r')
        #文件内容的每一行作为lines列表中的每一个元素保存
        lines = fr.readlines()
        fr.close
        flen = len(lines)
        #每一行遍历找出包含initStr的那些行并依此替换为replaceStr
        for i in range(flen): 
            if initStr in lines[i]:
                lines[i] = lines[i].replace(initStr, replaceStr)
                found = found +1
                #保存新的lines列表到文件中
        f = open(file, 'w')
        f.writelines(lines)
        f.close()
        for i in range(flen):
            if replaceStr in lines[i]:
                checked = checked +1
        if operator.ge(checked, found) == True:
            logging.info('Pass! 文件修改并保存成功!')
            return True
        else:
            logging.info('Fail! 文件失败')
            return False
    except Exception as ex:
        return False
        logging.error('***Error***: ',ex)
        
def copyFile(oldfile,newfile):
    try:
    #复制文件#oldfile和newfile都只能是文件
        shutil.copyfile(oldfile,newfile)
    except Exception as ex:
        print(ex)


def main():
    newfile = "test_"+str(time.strftime('%Y-%m-%d'))+".txt"
    startstr = ""
    for i in range(0,5):
        startstr = startstr + str(i) + ' ' * 20
    startstr = startstr+'\n'   
    createfile(newfile, startstr)
    x = os.popen('netstat -nao').read()
    #执行命令并读取内容:netstat -nao|findstr 3840
    appendfile(newfile, x)
    readfile(newfile)
    modifyFile(newfile, '0.0.0.0:0', '192.168.254.1')
    #clearfile(newfile)
    #removefile(newfile)


    
if __name__ == "__main__":
    main()




# 1. 熟练掌握文件夹/文件操作方法
# 2. 练习:
    #1)FOLDER的 创建/删除/修改/复制/移动
    #2)FILES的 创建/删除/修改/复制/移动



#coding=utf-8  
import operator
import sys,logging
import os
import time
import shutil
import re


def changeCWorkDir(path): #0.转换目录到给定的路径下
    '''Go to the defined directory path if current work directory is not the defined'''
    cwd = os.getcwd() #Get current working directory
    if cwd == path:
        print('-'*10, 'current working directory is already: ', cwd, '-'*10)
    else:
        if os.path.exists(path) == False:
            #检验给出的路径是否存在
            os.makedirs(path)
            print(path+'is not exist,'+'have created successfully!')
            # 如果不存在,创建这个给出的多级目录
    os.chdir(path)
    #转换目录到给定的路径下
    cwd = os.getcwd()
    #获取Python脚本工作的目录路径
    print('-'*10, 'current working directory is changed to: ', cwd, '-'*10)




def createfile():#1.创建新的文件
    '''create the file [yyy-mm-dd.docx] if file not exist\
in current working direcotry'''
    t = time.strftime('%Y-%m-%d')
    suffix = '.docx'
    newFile = os.getcwd()+'\\'+t+suffix
    if not os.path.exists(newFile):
        print('ready to create:')
        f = open(newFile, 'w')
        f.close()
        print(newFile+' created success.')
    else:
        print(newFile+' already exist.')
        return


def deleteNullfile():#2.删除空文件
    '''Delete all the file(s) with size = 0'''
    files = os.listdir(os.getcwd())
    #返回当前目录下的所有文件和目录名
    for file in files:
        print(file + ':' + str(os.path.getsize(file)))
        #打印文件/目录名及其大小
        if os.path.getsize(file) == 0: #get the size of the file, if 0, delete.
            #如果文件/目录大小为0kb
            if os.path.isfile(file) == True:
                os.remove(file) 
                #删除文件
                print(file+' deleted')
            else:
                print(file+' is not a file.')
        return


def deletebySize(minSize):#3.删除当前目录下文件大小<minSizeKB的文件及目录
    '''Delete the file(s) with size < minSize(Units:K) '''
    files = os.listdir(os.getcwd())
    #返回当前目录下的所有文件和目录名
    n = 0
    m = 0
    for file in files:
        print(file + ':' + str(os.path.getsize(file)))
        #打印出文件名及对应的大小
        n = n+1
        if os.path.getsize(file) < minSize * 1000:
            #获取文件大小<(minSize)KB 的文件
            if os.path.isfile(file) == True:
                os.remove(file) #删除文件
            elif os.path.isdir(file) == True:
                shutil.rmtree(file)
            m = m+1
            print(file+' has been deleted.')
    print('total '+str(n)+' files under the current directory. ', \
str(m)+' files <' +str(minSize)+'KB has been deleted.')


def deleteNullFileFolder(): #4.删除当前目录下的空文件及目录
    '''Delete all the file(s) with size = 0'''
    files = os.listdir(os.getcwd())
    #返回当前目录下的所有文件和目录名
    for file in files:
        print(file + ':' + str(os.path.getsize(file)))
        #打印文件/目录名及其大小
        if os.path.getsize(file) == 0: #get the size of the file, if 0, delete.
            #如果文件/目录大小为0kb
            if os.path.isdir(file) == True:
                #os.rmdir(file)#只能删除空目录
                shutil.rmtree(file)#删除空的/有内容的目录
            elif os.path.isfile(file) == True:
                os.remove(file) #删除文件
            print(file+' is deleted')


def deleteDir(filepath): #5. 删除多层空目录
    '''删除多层空目录'''
    if os.path.exists(filepath):
        shutil.rmtree(file)
        print(filepath+'is deleted successfully!') 
    else:
        print(filepath+'is already deleted!')


def renameFileFolder(oldname, newname): #6.重命名文件或目录
    #重命名文件/目录
    try:
        os.rename(oldname, newname)
    except Exception as ex:
        print(ex)


def copyFolder(olddir, newdir): #7.复制olddir目录/文件到指定目录newdir
    #olddir和newdir都只能是目录,且newdir必须不存在
    result = False
    if os.path.isdir(olddir) == True:
        if os.path.exists(newdir) == False and operator.contains(os.path.basename(newdir), '.') == False:
            shutil.copytree(olddir,newdir)
            result = True
            print('Pass! The old directory'+str(olddir)+' is copied to the new dir:' + str(newdir))
        else:
            result = False
            print('Failed! Because of the new dir '+str(newdir)+' is not a directory or already exist. \
Cannot copy the dir: ' +str(olddir)+' to new')
    #复制old文件到新的文件/目录olddir只能是文件,newdir可以是文件,也可以是目标目录
    elif os.path.isfile(olddir) == True:
        if os.path.exists(newdir) == False:
            os.makedirs(newdir)
        if os.path.isfile(newdir) == True:
            shutil.copy(olddir, newdir)
            result = True
            print('Pass! The old file '+str(olddir)+' is copied to the new file:' + str(newdir))
        elif os.path.isdir(newdir) == True:
            shutil.copy(olddir, newdir)
            result = True
            print('Pass! The old file '+str(olddir)+' is copied to the new dir:' + str(newdir))
        else:
            result = False
            print('Failed! The newdir is neither a directory nor a file, cannot copy old: '+str(olddir) +' to new:'+ str(newdir))
    else:
        result = False
        print('Failed! The olddir is neither a directory nor a file, cannot copy old: '+str(olddir) +' to new:'+ str(newdir))
    return result


def moveFileFolder(oldpos,newpos): #8.移动文件或目录
    try:
        shutil.move(oldpos,newpos)
    except Exception as ex:
        print('Error occured:', ex)




if __name__ == "__main__":
    hint = '''function:
    0. change currect working directory, if not exist, create a new one.
    1. create new file
    2. delete null file
    3. delete by size
    4. delete null file and folders
    5. delete directory with multiple levels
    6. rename file/folder
    7. copy folder
    8. move File/Folder
    q. quite\n
    please input number:'''
    while True:
        option = input(hint)
        if operator.eq(option, '0') == True:
            try:
                path= input('e.g. "D:\Test"\
Please input the directory you want to create/navigate:')
                changeCWorkDir(path)
            except ValueError as ex:
                print('ValueError:', ex)
        elif operator.eq(option, '1') == True:
            createfile()
        elif operator.eq(option, '2') == True:
            deleteNullfile()
        elif operator.eq(option, '3') == True:
            try:
                unit_size= input('minSize(K):')
                minSize = int(unit_size)
                deletebySize(minSize)
            except ValueError as e:
                print('ValueError:', e)
        elif operator.eq(option, '4') == True:
            deleteNullFileFolder()
        elif operator.eq(option, '5') == True:
            try:
                path= input('e.g. "D:\Test" Please input the directory you want to delete null file/folders:')
                deleteDir(path)
            except ValueError as ex:
                print('ValueError:', ex)
        elif operator.eq(option, '6') == True:
            try:
                oldname= input('e.g. "Test" Please input the old name of the file/folder:')
                newname = input('e.g. "AutoTest" Please input the new name of the file/folder:')
                renameFileFolder(oldname, newname)
            except ValueError as ex:
                print('ValueError:', ex)
        elif operator.eq(option, '7') == True:
            try:
                olddir= input('e.g. "D:\Test" Please input the old folder:')
                newdir = input('e.g. "D:\AutoTest" Please input the new folder:')
                copyFolder(olddir, newdir)
            except ValueError as ex:
                print('ValueError:', ex)
        elif operator.eq(option, '8') == True:
            try:
                oldpos= input('e.g. "D:\Test" Please input the old folder:')
                newdir = input('e.g. "D:\AutoTest" Please input the new folder:')
                moveFileFolder(oldpos,newpos)
            except ValueError as ex:
                print('ValueError:', ex)
        elif operator.eq(option, 'q') == True:
            print('quit!')
            break
        else:
            print('disabled input. please try again...')
    






猜你喜欢

转载自blog.csdn.net/yinshuilan/article/details/79544931