下面小编为大家整理了Python删除指定目录下过期文件的2个脚本(共含7篇),欢迎阅读与借鉴!同时,但愿您也能像本文投稿人“woooyou”一样,积极向本站投稿分享好文章。
python连接MySQL、MongoDB、Redis、memca
python list转dict示例分享
python str与repr的区别
python读取Android permission文件
Python 正则表达式操作指南
可用于监控 mysql Master Slave 状态的py
easy_install python包安装管理工具介绍
python文件比较示例分享
tornado捕获和处理404错误的方法
python解析xml模块封装代码
Python入门教程 超详细1小时学会
python 中文乱码问题深入分析
比较详细Python正则表达式操作指
Python字符串的encode与decode研
Python open读写文件实现脚本
Python enumerate遍历数组示例应
Python 深入理解yield
Python+Django在windows下的开发
python 文件和路径操作函数小结
python 字符串split的用法分享
这篇文章主要介绍了Python实现删除文件但保留指定文件,本文直接给出实现代码,并同时给出代码解释,需要的朋友可以参考下
由于给客户的发布版本上客户改动了些代码和图片,我们这边给他们更新publish都是增量更新(开发提供更新指定的文件,我们提取出来给客户进行覆盖更新),但有时需要更新的文件较多导致不得不一个一个的进行查找、替换,工作量大而且容易出错,所以用python写个保留pulish后目录的指定文件、删除其他文件的功能。
代码如下:
代码如下:
import os
import os.path
def DeleteFiles(path,fileList):
for parent,dirnames,filenames in os.walk(path):
FullPathList = []
DestPathList = []
for x in fileList:
DestPath = path + x
DestPathList.append(DestPath)
for filename in filenames:
FullPath = os.path.join(parent,filename)
FullPathList.append(FullPath)
for xlist in FullPathList:
if xlist not in DestPathList:
os.remove(xlist)
代码解释:
1、for parent,dirnames,filenames in os.walk(path): 该for循环用于遍历指定path的父文件夹、文件夹名(不含目录)、文件名
2、
代码如下:
for x in fileList:
DestPath = path + x
DestPathList.append(DestPath)
该方法两个参数分别是path,filelist,
path用来指定publish文件的存放目录,例如:‘D:publish‘,filelist通过list存放你希望保留的文件及该文件路径,例如:
[r‘1.txt‘,r‘a1.txt‘],然后将path和filelist拼接起来存放到另一个列表中就是你希望保存文件的完整路径存放在DestPathList中,既[‘D:publish1.txt‘,‘D:publisha1.txt‘]
3、
代码如下:
for filename in filenames:
FullPath = os.path.join(parent,filename)
FullPathList.append(FullPath)
将目录下所有文件的绝对路径存放在列表FullPathList中
4、
代码如下:
for xlist in FullPathList:
if xlist not in DestPathList:
os.remove(xlist)
遍历FullPathList中元素跟DestPathList中元素进行比对,如果不相同则删除文件
功能虽然简单,但工作中还是比较实用的,故在此留下脚印。
作者:work24 字体:[增加 减小] 类型:
这篇文章主要介绍了python对指定目录下文件进行批量重命名的方法,涉及Python中replace及join方法的使用技巧,非常具有实用价值,需要的朋友可以参考下
本文实例讲述了python对指定目录下文件进行批量重命名的方法,分享给大家供大家参考。具体如下:
这段python代码可对c:temp目录下的所有文件名为”scroll_1”文件替换为”scroll_00”
import spath = ‘c:temp‘for file in os.listdir(path): if os.path.isfile(os.path.join(path,file))==True: newname = file.replace(“scroll_1”, “scroll_00”) os.rename(os.path.join(path,file),os.path.join(path,newname)) print(file)
希望本文所述对大家的Python程序设计有所帮助,
Shell脚本递归打印指定目录中所有目录文件#!/bin/bash#递归打印当前目录下的所有目录文件,
python文件读写并使用mysql批量插入示例分
Python实现多线程下载文件的代码实例
Python中使用动态变量名的方法
Python读取图片EXIF信息类库介绍和使用实
python算法学习之计数排序实例
python数据库操作常用功能使用详解(创建表
python实现的解析crontab配置文件代码
python实现巡检系统(solaris)示例
python线程锁(thread)学习示例
Python常见文件操作的函数示例代码
Python入门教程 超详细1小时学会
python 中文乱码问题深入分析
比较详细Python正则表达式操作指
Python字符串的encode与decode研
Python open读写文件实现脚本
Python enumerate遍历数组示例应
Python 深入理解yield
Python+Django在windows下的开发
python 字符串split的用法分享
python 文件和路径操作函数小结
这篇文章主要介绍了Python文件和目录操作详解,本文讲解了文件的打开和创建、文件的读取、文件的写入、内容查找替换等内容,需要的朋友可以参考下
一、文件的打开和创建
1、打开
代码如下:
open(file,mode):
>>>fo = open(‘test.txt‘, ‘r‘)
>>>fo.read
‘hellon‘
>>>fo.close()
file(file,mode):
>>>f = file(‘test.txt‘, ‘r‘)
>>>f.read()
‘hellon‘
>>>f.close()
mode可取值:
2、创建
用w/w+/a/a+模式打开即可,
二、文件的读取
1、String = FileObject.read([size])
代码如下:
>>> fr = open(‘test.txt‘)
>>> fr.read()
‘hellonworldn‘
or:
代码如下:
>>> for i in open(‘test.txt‘):
... print i
...
hello
world
2、String = FileObject.readline([size])
代码如下:
>>> f = open(‘test.txt‘)
>>> f.readline()
‘hellon‘
>>> f.readline()
‘worldn‘
>>> f.readline()
‘‘
或者可以用next
3、List = FileObject.readlines([size])
代码如下:
>>> f = open(‘test.txt‘)
>>> f.readlines()
[‘hellon‘, ‘worldn‘]
三、文件的写入
1、write(string)
代码如下:
>>> f = open(‘test.txt‘, ‘a‘)
>>> f.write(‘hellonworld‘)
#‘hellonworld‘
2、writelines(list)
代码如下:
>>> l = [‘a‘,‘b‘,‘c‘]
>>> f=open(‘test.txt‘,‘a‘)
>>> f.writelines(l)
#‘hellonworldabc‘
注:writelines相当于调用了多次write,不会自动添加换行(n)符
四、内容查找替换
1、FileObject.seek(offset, mode)
offset:偏移量
mode:
0表示将文件指针指向从文件头部到“偏移量”字节处,
1表示将文件指针指向从文件当前位置向后移动“偏移量”字节,
2表示将文件指针指向从文件尾部向前移动“偏移量”字节。
代码如下:
>>> f=open(‘test.txt‘)
>>> f.read()
‘hellonworldabc‘
>>> f.read()
‘‘
>>> f.seek(0,0)
>>> f.read()
‘hellonworldabc‘
>>> f.close()
2、flush:提交更新,即在文件关闭之前把内存中的内容强制写入文件(一般是文件关闭后写入)
3、文件查找:遍历行进行查找
代码如下:
#!/usr/bin/python
import re
search=‘hello world‘
file=‘test.txt‘
count = 0
f = open(file)
for l in f.readlines():
li = re.findall(search,l)
if len(li) > 0:
count += len(li)
print “Search ” + str(count) + “ ”“ + search + ”“”
f.close()
4、文件内容替换:遍历行进行替换
替换到新文件demo:
代码如下:
#!/usr/bin/python
s=‘hello‘
f=‘test.txt‘
rs=‘ten‘
rf=‘test2.txt‘
fh = open(of)
newl=[]
for l in ofh.readlines():
nl = l.replace(os,rs)
newl.append(nl)
rfh = open(rf,‘w+‘)
rfh.writelines(newl)
ofh.close()
rfh.close()
替换到原文件demo:
代码如下:
[server@localserver file]$ cat test.txt
abc
hello
world
hello world
helloworld
hello hello world
[server@localserver file]$ cat fr.py
#!/usr/bin/python
s=‘hello‘
file=‘test.txt‘
rs=‘ten‘
f = open(file, ‘r+‘)
s=f.read()
f.seek(0,0)
f.close()
f = open(file, ‘w+‘)
f.write(s.replace(os,rs))
f.close()
[server@localserver file] python fr.py
[server@localserver file]$ cat test.txt
abc
ten
world
ten world
tenworld
ten ten world
这里采用了重建文件的办法,
或用 fileinput 模块直接在原文件上修改:
代码如下:
#!/usr/bin/python
import fileinput
s=‘hello‘
file=‘test.txt‘
rs=‘ten‘
for line in fileinput.input(file, inplace=True):
print line.replace(os,rs).replace(‘n‘,‘‘)
注意,这里删除了n是因为print时会写入换行。
五、文件及目录操作
一般是借助OS模块实现
1、mkdir(path[,mode=0777]):创建目录,相当于mkdir
代码如下:
>>>import os
>>>os.mkdir(‘tt‘)
2、makedirs(name[, mode=511]):创建多级目录,相当于mkdir -p
3、rmdir(path):删除目录,相当于rm
4、removedirs(path):删除多级目录,相当于rm -rf
5、listdir(path):列出目录中文件和文件夹,相当于ls
6、getcwd():获取当前路径,相当于pwd
7、chdir(path):切换目录,相当于cd
8、rename(src, dst):重命名
9、shutil.copyfile(str,dst):复制文件(要引入shutil模块)
10、path.splitext(filename):获取文件路径和扩展名
代码如下:
>>> import os
>>> fileName, fileExtension = os.path.splitext(‘/path/to/somefile.ext‘)
>>> fileName
‘/path/to/somefile‘
>>> fileExtension
‘.ext‘
11、walk(top, topdown=True, nerror=None):遍历目录
代码如下:
>>> import os
>>> g = os.walk(‘a‘)
>>> g.next()
(‘a‘, [‘b‘], [])
>>> g.next()
(‘a/b‘, [‘f‘, ‘c‘], [])
>>> g.next()
(‘a/b/f‘, [], [‘3.txt‘])
>>> g.next()
(‘a/b/c‘, [‘d‘, ‘e‘], [])
>>> g.next()
(‘a/b/c/d‘, [], [‘1.txt‘])
>>> g.next()
(‘a/b/c/e‘, [], [‘2.txt‘])
walk返回的是一个生成器,生成器中的内容是:当前目录,目录列表,文件列表
python自己递归实现文件遍历:
代码如下:
#!/usr/bin/python
import os
def dirList(path):
filelist = os.listdir(path)
fpath = os.getcwd()
allfile = []
for filename in filelist:
filepath = os.path.abspath(os.path.join(path, filename))
if os.path.isdir(filepath):
allfile.extend(dirList(filepath))
else:
allfile.append(filepath)
return allfile
files = dirList(‘a‘)
print files
引言
有个需要,需要把某个目录下的目录结构进行复制,不要文件,当目录结构很少的时候可以手工去建立,当目录结构复杂,目录层次很深,目录很多的时候,这个时候要是还是手动去建立的话,实在不是一种好的方法,弄不好会死人的,写一个python脚本来处理吧。
首先了解
写python脚本前,先了解几个东西
#!/usr/bin/python
这个东西写过脚本的人都知道,用来标明该脚本的执行器,类似的还有
#!/bin/bash 通过bash来执行
#!/usr/local/php/bin/php 通过php执行器来执行
# -*- coding: utf-8 -*-
这个是设置脚本的编码格式,不然非英文可能会出现乱码
匿名函数lambda
#lambda很好用,创建匿名函数很方便
g = lambda x,y : x+y
g(3,5) #返回8
匿名函数分为四部分,标识 lambda,分号 :,参数 x,y,操作 x+y
除了这个之外,还有函数map、filter一个进行映射,一个进行过滤
__name__==“__main__”
一个文件就是一个模块,在python中每个模块都有一个__name__属性,属性的值取决于如何使用该模块,一般有两种使用方式,直接在命令行运行,这个时候__name__值为__main__,当import使用的时候,__name__值就是当前模块的名称(不带扩展名),因此可以通过这个判断是否是直接在命令行运行程序,以便做一些脚本使用。
import os
import sys
还有这两个模块,os包含一些操作系统功能,比如说遍历文件夹,拼接路径等等,sys模块包含系统函数,我这里只用来获取脚本后面的参数
编码
#!/usr/bin/python
# -*- coding: utf-8 -*-
#Filename:floders.py
import os
import sys
source = os.path.realpath(sys.argv[1])
target = os.path.realpath(sys.argv[2])
def isdir(x):
return os.path.isdir(x) and x != '.svn'
def mkfloders(src,tar):
paths = os.listdir(src)
paths = map(lambda name:os.path.join(src,name),paths)
paths = filter(isdir, paths)
if(len(paths)<=0):
return
for i in paths:
(filepath, filename)=os.path.split(i)
targetpath = os.path.join(tar,filename)
not os.path.isdir(targetpath) and os.mkdir(targetpath)
mkfloders(i,targetpath)
if __name__==“__main__”:
if(os.path.isdir(source)):
if(target.find(source) == 0):
print(“不能将生成的新目录放在源目录下”)
else:
if not os.path.isdir(target):
os.mkdir(target)
mkfloders(source,target)
else:
print(“源文件夹不存在”)
使用
使用很简单:
#在当前文件夹下执行
./folders.py ./ /tmp/yyyyy
#执行完之后就会在/tmp下创建yyyyy目录,目录中包含上面的第一个文件夹中的目录结构
这个地方有两个要注意的地方,不能将创建后的目录放在要复制的目录中或者其子目录中
总结
在做这个的时候遇到了这个问题 /usr/bin/python^M: bad interpreter: No such file or directory ,这个问题看样子是编码的问题,在每行后面添加了个字符,查资料后,原来是由于我从windows下直接把程序复制到linux下的编码出现了问题,解决方法很简单:vi folders.py之后,在命令行下输入
:set ff #结果表示编码平台,应该是fileformat=dos
:set fileformat=unix #设置编码到unix平台
:set ff #这个时候再去查看文件编码,应该是fileformat=unix