Python3 文件处理相关脚本
对文件相关处理是脚本中最常见的,下面列举几种实用的案例:
批量删除:
(1)删除指定目录,指定后缀文件
例:删除目录J:/start下的 .log与.tmp结尾文件
def del_files(path, filters):
if os.path.exists(path) and os.path.isdir(path):
for root, dirs, files in os.walk(path):
for name in files: # name.find(".tmp")>0
for subfix in filters:
if name.endswith(subfix):
os.remove(os.path.join(root, name))
print ("Delete File: " + os.path.join(root, name)) def test_del_files():
filters = [".log",".tmp"]
del_files("J:/StartUML",filters)
(2)只保留特定文件
def del_all(dir, retain_file):
if os.path.exists(dir) and os.path.isdir(dir):
dir_content = [x for x in os.listdir(dir) if x != retain_file]
for f in dir_content:
fpath = os.path.join(dir, f)
if os.path.isdir(fpath):
shutil.rmtree(fpath)
else:
os.remove(fpath) del_all("J:/StartUML","11.txt")
批量复制与移动:
(1)复制处理:
#方案一
def copy_all(sourceDir,targetDir):
if os.path.exists(sourceDir):
for file in os.listdir(sourceDir):
sourceFile = os.path.join(sourceDir, file)
targetFile = os.path.join(targetDir, file)
if os.path.isfile(sourceFile):
if not os.path.exists(targetDir):
os.mkdir(targetDir)
# 如果目的路径里面不存在某个文件或者存在那个同名文件但是文件有残缺,则复制,否则跳过
if not os.path.exists(targetFile) or \
(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
shutil.copy(sourceFile,targetFile)
if os.path.isdir(sourceFile):
copy_all(sourceFile, targetFile) #方案二
def copy_files(src_dir,dest_dir,isonelevel):
if os.path.exists(src_dir) and os.path.isdir(src_dir):
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
for parent, dirnames, filenames in os.walk(src_dir):
# if parent.startswith(src_dir):
if isonelevel:
dstdir = dest_dir
else:
dstdir = parent.replace(src_dir,dest_dir,1)
for dirname in dirnames:
os.mkdir(os.path.join(dstdir,dirname))
for fname in filenames:
shutil.copy(os.path.join(parent, fname), os.path.join(dstdir, fname)) # copy_all("J:/ZIMU","J:/StartUML")
(2)移动处理
#walk遍历处理实现
def move_files(src_dir, dst_dir):
if os.path.exists(src_dir) and os.path.isdir(src_dir):
if not os.path.exists(dst_dir):
os.mkdir(dst_dir)
for pdir ,dirs, fnames in os.walk(src_dir,topdown=True):
newdstdir = pdir.replace(src_dir,dst_dir,1)
if not os.path.exists(newdstdir):
os.mkdir(newdstdir)
for fn in fnames:
os.rename(os.path.join(pdir,fn),os.path.join(newdstdir,fn))
for dir in dirs:
dstSource = os.path.join(newdstdir,dir)
if not os.path.exists(dstSource):
os.mkdir(dstSource)
shutil.rmtree(src_dir) #递归实现
def move_recursive(sourceDir,targetDir):
if os.path.exists(sourceDir):
for file in os.listdir(sourceDir):
sourceFile = os.path.join(sourceDir, file)
targetFile = os.path.join(targetDir, file)
if not os.path.exists(targetDir):
os.mkdir(targetDir)
if os.path.isfile(sourceFile):
os.rename(sourceFile,targetFile)
elif os.path.isdir(sourceFile):
move_recursive(sourceFile,targetFile) def move_all(sourceDir,targetDir):
move_recursive()
shutil.rmtree(sourceDir) # move_all("J:/StartUML/AGirls","J:/StartUML/ABoys")
搜索与查找:
(1)查找指定文件名称文件
# 指定目录及其子目录中查找文件名含有关键字的文件
def search_file_pattern_name1(path, word):
for filename in os.listdir(path):
fp = os.path.join(path, filename)
if os.path.isfile(fp) and word in filename:
print(fp)
elif os.path.isdir(fp):
search_file_pattern_name1(fp, word) # search_file("J:/AndroidSrc4.2/packages" ".png")
def search_file_pattern_name2(dirname,keyworld):
results = []
for root, dirs, files in os.walk(dirname):
results += [os.path.relpath(os.path.join(root, x), start = dirname) for x in files if keyworld in x]
for result in results:
print(result)
(2)查找文本内容包含指定关键词的所以文件,输出该文件路径
def search_file_txtcontent1(dir, word,isaccurate):
if os.path.exists(dir):
for filename in os.listdir(dir):
fp = os.path.join(dir, filename)
if os.path.isfile(fp):
with open(fp) as f:
num = 0
for line in f:
num += 1
if word in line:
if isaccurate:
dSearch = line.split()
for search_word in dSearch:
if search_word == word:
print ("accurate find word ", "fileneme=",filename, " line =" , num)
else:
print ("blur find word ", "fileneme=", filename, " line =", num)
# break
elif os.path.isdir(fp):
search_file_txtcontent1(fp, word,isaccurate) # search_file_txtcontent1("J:/AndroidSrc4.2/packages/apps/Launcher2" ,"onCreate",False) # fileinput模块可以遍历文本文件的所有行.它的工作方式和readlines很类似,不同点在于,
# 它不是将全部的行读到列表中而是创建了一个xreadlines对象.
def search_file_txtcontent2(dir_path,searchKey,isaccurate):
# pattern = "\d{3}-\d{3}-\d{4}" # 如800-333-1212
if os.path.exists(dir_path):
for pdir, subdirs, subfiles in os.walk(dir_path):
for fname in subfiles:
fn = os.path.join(pdir,fname)
if os.path.splitext(fn)[1] == ".java":
finput = fileinput.input(fn)
for eachline in finput:
if isaccurate:
for m in re.finditer(r"\bonCreate\b", eachline):
if m.group(0):
print("accurate find ============")
print ('filename:', fileinput.filename(), 'line:', fileinput.lineno(), eachline)
else:
a = re.search(searchKey, eachline)
if a:
print("============")
print ('filename:', fileinput.filename(), 'line:', fileinput.lineno(), eachline) # search_file_txtcontent2("J:/AndroidSrc4.2/packages/apps/Launcher2","onCreate",True)
(3)文本替换处理,将文本内指定原内容替换为新的内容
#方案一,单文件处理
def search_replace_content(src_file, oldWorld, newWorld):
if os.path.exists(src_file):
# print("tempfile name is", "=>", file) # TemporaryFile创建的临时文件的名字
if os.path.exists(src_file):
fopen = open(src_file, 'r')
else:
print("file %s not found" % src_file)
sys.exit() temp_file = tempfile.mktemp()
file_dst = open(temp_file, 'w+b') # 打开临时文件
for line in fopen:
line = re.sub(oldWorld, newWorld, line)
file_dst.write(line) # 把替换后的内容写入到临时文件中
fopen.close()
file_dst.seek(0)
file_dst.close() if os.path.exists(src_file):
os.remove(src_file)
shutil.copy(temp_file, src_file) # copy临时文件到原文件
try:
os.remove(temp_file) # 删掉临时文件
except OSError:
pass #方案二,多文件处理
def search_replace_bigtxt(dir_search,oldKey, newKey):
for parent_dir, subdirs, files in os.walk(dir_search):
for file in files:
fname = os.path.join(dir, file)
inFile = codecs.open(fname, "r", "utf-8")
outFile = codecs.open(fname + ".new", "w", "utf-8")
for line in inFile:
newline = line.replace(oldKey, newKey)
outFile.write(newline)
inFile.close()
outFile.close()
os.rename(fname + ".new", fname)
多组词替换处理
def easy2_replace_txt():
replacements = {'zero': '0', 'temp': 'bob', 'garbage': 'nothing'}
with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
outfile.write(line)
Python3 文件处理相关脚本的更多相关文章
- 将 Python3 文件打包成 exe 文件
我们用 Python 写好的代码,如何给别人在没有配置 Python 环境的情况下直接使用呢?尤其是面向 windows 众. 因为 Python 是一门解释性的语言,离开了 Python 解释器,P ...
- linux用户、文件权限相关命令
root 现代操作系统一般属于多用户的操作系统,也就是说,同一台机器可以为多个用户建立账户,一般这些用户都是为普通用户,这些普通用户能同时登录这台计算机,计算机对这些用户分配一定的资源. 普通用户在所 ...
- shell基础、变量、相关脚本
目录 一.shell基础 书写规范 引号 配置文件 read交互 脚本调式 小节总结 二.变量 变量类型 位置变量 状态变量 替换和删除 变量补充 变量运算 小节总结 三.相关脚本面试题 统计hist ...
- 【转载】]基于RedHatEnterpriseLinux V7(RHEL7)下SPEC CPU 2006环境搭建以及测试流程 介绍、安装准备、安装、config文件以及运行脚本介绍
https://www.codetd.com/article/1137423 <版权声明:本文为博主原创文章,未经博主允许不得转载> 本次利用SPECCPU2006测试工具来进行Intel ...
- 【转载】基于RedHatEnterpriseLinux V7(RHEL7)下SPEC CPU 2006环境搭建以及测试流程(之一)——介绍、安装准备、安装、config文件以及运行脚本介绍
基于RedHatEnterpriseLinux V7(RHEL7)下SPEC CPU 2006环境搭建以及测试流程(之一)--介绍.安装准备.安装.config文件以及运行脚本介绍 其他 2018-0 ...
- Shell文件权限和脚本执行
一.预备知识 1.shell的作用 2.常识 (1)Tab键自动补全 使用Terminal时,输入命令的前几个字母,敲tab会自动补全命令或文件名.目录等. 好处:操作速度更快:不容易出错: ...
- 一个获取指定目录下一定格式的文件名称和文件修改时间并保存为文件的python脚本
摘自:http://blog.csdn.net/forandever/article/details/5711319 一个获取指定目录下一定格式的文件名称和文件修改时间并保存为文件的python脚本 ...
- unity3d 特殊文件夹和脚本编译顺序
unity3d 特殊文件夹和脚本编译顺序 转自http://blog.csdn.net/u010019717/article/details/40474631 大多数情况下,您可以选择任何你喜欢的文件 ...
- 初步学习nodejs,业余用node写个一个自动创建目录和文件的小脚本,希望对需要的人有所帮助
初步学习nodejs,业余用node写个一个自动创建目录和文件的小脚本,希望对需要的人有所帮助,如果有bug或者更好的优化方案,也请批评与指正,谢谢,代码如下: var fs = require('f ...
- 自动删除超过30天文件的vbs脚本【转发】
利用代码制作自动删除超过30天的文件及文件夹的vbs脚本,定期清理文件夹中长时间无用文件. 1.首先在新建一个文本文档,粘贴代码(代码可通过添加微信公众号vbs_edit(VBS脚本之家)回复018获 ...
随机推荐
- VMware-SSH协议的认证方式
SSH1协议支持非对称密钥认证方式.口令认证,无法保证连接的完整性. SSH2协议支持SSH1协议支持的所有认证方式,增加数据保密性. 基于主机的认证方式[!不安全!] 当本地计算机收到执行远程命令的 ...
- 统计tomcat的access日志
统计tomcat的access日志的ip次数,并按次数排序 awk '{sum[$1]++}END{for(i in sum) print i "\t" sum[i]}' loca ...
- transformers 之Trainer对应的数据加载
基础信息说明 本文以Seq2SeqTrainer作为实例,来讨论其模型训练时的数据加载方式 预训练模型:opus-mt-en-zh 数据集:本地数据集 任务:en-zh 机器翻译 数据加载 Train ...
- 【Frida】打印方法的调用堆栈
function printstack() { console.log(Java.use("android.util.Log").getStackTraceString(Java. ...
- Qt使用图片旋转绘制圆环,圆弧类UI界面(方法可适用于winform和WPF等其余UI绘制)
先上效果图: 这个主要是一个试剂杯盘的循环图,相信大家伙一定都想到了使用GDI和三角函数来进行计算,但如果没有实际尝试,可能会踩一些坑,留此文帮助大家方便快捷的绘制出类似圆环的UI效果. 这里主要是使 ...
- SpringBoot Circular view path错误
在运行SpringBoot时报了这样一个错误 百度翻译是视图循环 搜索一下 原来是类上restcontroller写成了controller 对比一下两者 @Controller和@RestCont ...
- [前端js] 爬取亿图脑图大纲
这段程序使看到了好的东西,又没有零钱的产物 还是老师让画思维导图我不想画还想白嫖的想法 用时20分钟 就拿这个来作为例子 https://mm.edrawsoft.cn/template/286842 ...
- shell语法3-expr命令、read命令、echo命令
一.expr命令(注:常常配合``或者$()来取得所求的值) 1.expr用于求表达式的值:expr 表达式 注意: (1)用空格隔开每一项(2)用反斜杠放在shell特定的字符前面(发现表达式运行错 ...
- java泛型元组
package generics;class Amphibian{};class Vehicle{};public class TupleTest { static TwoTuple<Strin ...
- uniapp(1)
**在项目根目录中新建.gitignore忽略文件,并配置如下: 忽略 node_modules /node_modules /unpackage/dist** 添加页面 新建页面,而后选择scss模 ...