Python文件及文件夹处理
Python文件及文件夹处理
# 50.python执行shell脚本返回结果
# import subprocess
# result=subprocess.getoutput('dir')
# print(result)
# #######################################################################################################################
# 51.输出某个路径下所有文件和文件夹的路径
# import os
# def print_dir():
# filepath=input('请输入路径:')
# if filepath=='':
# print('请输入正确的路径')
# else:
# for i in os.listdir(filepath):
# print(os.path.join(filepath,i))
# print(print_dir())
# #######################################################################################################################
# 52.输出某个路径下及其目录下的所有文件路径
# import os
# def show_dir(filepath):
# for i in os.listdir(filepath):
# path=(os.path.join(filepath,i))
# print(path)
# if os.path.isdir(path): # 判断是否是目录
# show_dir(path) # 如果是目录,采用递归的方式
# filepath='C:\Program Files'
# show_dir(filepath)
# #######################################################################################################################
# 53.列出当前目录下所有目录及文件夹名
# import os
# for d in os.listdir('.'):
# print(d)
# #######################################################################################################################
# 54.输出某个路径及其子目录下所有以html为后缀的文件
# import os
# def print_dir(filepath):
# for i in os.listdir(filepath):
# path=os.path.join(filepath,i) # path为路径
# if os.path.isdir(path): # 判断是否是文件夹,如果是文件夹则递归,如果不是文件夹则执行下一行
# print_dir(path)
# if path.endswith('.html'): # 判断文件是否是html
# print(path)
#
# filepath='C:/Users/Administrator/PycharmProjects/python进阶'
# print_dir(filepath)
# #######################################################################################################################
# 55.生成100个数,然后写入文件
# import random
# fp=open('aa.txt','w')
# for i in range(1,101):
# n=random.randint(1,1000)
# fp.write(str(i)+'->'+str(n)+'\n')
# fp.close()
# #######################################################################################################################
# 56.逐行读入utf-8编码的文件打印在屏幕上
# # coding=utf-8
# import chardet # 查看字符串编码方式的模块
# fp=open('abc.txt','r')
# lines=fp.readlines()
# fp.close()
#
# for line in lines:
# print(line.decode('utf-8').encode('gbk','ignore'))
# #######################################################################################################################
# 57.删除文件
# import os
# file=r'C:\Users\Administrator\PycharmProjects\python进阶\ab.txt'
# if os.path.exists(file):
# os.remove(file)
# print('delete sucess')
# else:
# print('no such file:%s' % file)
# #######################################################################################################################
# 58.获取当前目录
# import os
# os.getcwd() # 获取当前目录
# #######################################################################################################################
# 59.修改当前目录,
# import os
# os.chdir('C:\Users\Administrator\PycharmProjects\python进阶') # 更改目录
# #######################################################################################################################
# 60.以相反顺序展示一个文件的内容
# for line in reversed(list(open('c.txt'))):
# print(line.rstrip)
# #######################################################################################################################
# 61.设置一个函数,返回给定文件的后缀名
# def get_suffix(filename,has_dot=False):
# pos=filename.rfind('.') # 返回数值pos
# if 0<pos<len(filename)-1:
# index=pos if has_dot else pos+1 # 返回pos+1
# return filename[index:]
# else:
# return ''
# print(get_suffix('vbgedfvbda.txt'))
# 精简版
# def get_suffix(filename,has_dot=False):
# pos = filename.rfind('.') # 返回数值pos
# index = pos+1 # 返回pos+1
# return filename[index:]
# print(get_suffix('vbgedfvbda.txt'))
# #######################################################################################################################
# 62.返回给定文件的后缀名os.path.splitext(file) 返回元组 <class 'tuple'>
# import os
# print(os.path.splitext('a.yxy'),type(os.path.splitext('a.yxy')))
#
# print(os.path.splitext('a.yxy')[1])
# #######################################################################################################################
# 63.返回给定文件的后缀名
# a = 'vbgedfvbda.txt'
# pos=a.rfind('.')
# print(a[pos:])
# #######################################################################################################################
# 64.生成随机数
# import random
# print(random.random()) # 0~1之间浮点型随机数
# print(random.randint(2,4)) # 2~4之间整形随机数
# print(random.randrange(2,8,2)) # step=2的随机数
# print(random.uniform(10,20)) # 10~20浮点型随机数
# print(random.choice('dnnjksjkji')) # 随即提取一个字符
# #######################################################################################################################
# 65.从指定序列中随机获取指定长度的片段
# import random
# list1=[1,2,4,'edd',56,'da']
# print(random.sample(list1,3)) # 指定序列中随机获取指定长度的片段
# print(random.sample(list1,3)) # 指定序列中随机获取指定长度的片段
# print(random.sample(list1,3)) # 指定序列中随机获取指定长度的片段
# print(random.sample(list1,3)) # 指定序列中随机获取指定长度的片段
# #######################################################################################################################
# 66.打乱一个排好序的list对象
# import random #
# list2=[23,5,55,756,211,131] # 列表
# random.shuffle(list2) # 打乱列表
# print(list2) # 打乱列表
# random.shuffle(list2) # 打乱列表
# print(list2)
# random.shuffle(list2)
# print(list2)
# random.shuffle(list2)
# print(list2)
# #######################################################################################################################
# 67.生成验证码的两种方式
# import random
# list3=[]
#
# for i in range(65, 91): # A-Z
# list3.append(chr(i))
# for j in range(97, 123): # a-z
# list3.append(chr(j))
# for k in range(48, 58): # 0-9
# list3.append(chr(k))
#
# ma = random.sample(list3, 6) # 指定序列中随机获取指定长度的片段
# print(ma)
# ma = ''.join(ma)
# print(ma)
# #######################################################################################################################
# 装饰器 @
# 68.以函数为参数返回一个替换函数的可执行函数
# #######################################################################################################################
# 构造器 def __init__(self,,,,):
# #######################################################################################################################
# 69.类传入外部参数全靠构造函数
# class fib:
# def __init__(self):
# self.xxt=29
#
# f=fib()
# print(f.xxt)
# 类
# ######################################################################
# class fib: #
# def __init__(self,name): #
# self.age=29 #
# self.sex='femal' #
# self.value=name #
# #
# f=fib('xxt') #
# print('name',f.value,'\n','age',f.age,'\n','sex',f.sex) #
# print('name',f.value,'\t','age',f.age,'\t','sex',f.sex) #
# ######################################################################
# #######################################################################################################################
# 生成器 Generator
# 70.简单生成器
# L=[x*x for x in range(3)] # 列表
# g=(x*x for x in range(3)) # 迭代器
#
# print(L) # 列表可直接打印
# print(g) # 迭代器不能直接打印
# for i in g: # 循环打印
# print(i) # 循环打印
# #######################################################################################################################
# 70.带有yield语句的生成器 return返回值时不保留当前信息,yield返回值时会保留当前信息
# import sys # 跟编译器相关
# def fibobacci(n):
# a, b, counter = 0, 1, 0
# while True:
# if ( counter > n ):
# return
# yield a # 带有yield语句的生成器 return返回值时不保留当前信息,yield返回值时会保留当前信息
# a, b = b, a+b # 先计算右边再复制给左边
# counter += 1
#
# f=fibobacci(10)
#
# while True:
# try:
# print(next(f), end='\t')
# except StopIteration:
# sys.exit()
# #######################################################################################################################
# 迭代器 有两个基本语法 iter()和next()可以使用collections模块判断一个对象是否是迭代器
# 71. 简单的迭代器
# list=[1,2,3,4]
# it=iter(list)
# for x in it:
# print(x)
# #######################################################################################################################
# 71. 判断迭代器 isinstance
# from collections import Iterable
#
# print(isinstance('asdfc',Iterable)) # True
# print(isinstance([1,23,444],Iterable)) # True
# print(isinstance(2332,Iterable)) # False
# print(isinstance((1,2,45,6),Iterable)) # True
# print(isinstance({1,23,53,12},Iterable)) # True
# #######################################################################################################################
# 71. 类的迭代使用,需要__iter__和__next__
# class MyNumbers:
# def __iter__(self):
# self.a=1
# return self
#
# def __next__(self):
# x=self.a # self.a=1
# self.a+=1 # self.a+=1
# return x # 返回的x在print中打印
#
# myclass = MyNumbers()
# myiter = iter(myclass)
#
# print(next(myiter))
# print(next(myiter))
# print(next(myiter))
# print(next(myiter))
# print(next(myiter))
# #######################################################################################################################
# 72.isinstance和type检测某一变量是否是某一类型,某一实例是否属于某一类
# a=10
# print(type(a)==int) # type(a)==int
# print(isinstance(a,int)) # isinstance(a,int)
# print(isinstance(a,str)) #
# print(isinstance(a,(str,int,list))) # isinstance(a,(str,int,list))
# #######################################################################################################################
# # 73.浅拷贝、深拷贝、赋值
# import copy
# a=[1,2,3,4,['a','b']]
# b=a # a,b完全是一个东西
#
# c=copy.copy(a) # 浅拷贝
# # 增加列表元素 不能浅拷贝
# # 列表的某个元素更改 可以浅拷贝
#
# d=copy.deepcopy(a) # 单独拷贝a一份,拷贝结束,不在有关联,为初始a=[1,2,3,4,['a','b']]
#
# a.append(5) # 增加列表元素 不能浅拷贝
# a[4].append('c') # 列表的某个元素更改 可以浅拷贝
# a[0]=66
#
# print('a=',a)
# print('b=',b)
# print('c=',c)
# print('d=',d)
# #######################################################################################################################
# #################################################################
# # # 74.map函数,根据提供函数对指定序列进行映射,相当于一次性求解多个值 ##
# def square(x): ##
# return x**2 ##
# ##
# print(list(map(square,[1,2,3,4,5]))) # square后无括号 ##
# print(list(map(lambda x:x**2,[1,2,3,4,5]))) ##
# ##
# print(list(map(lambda x,y:x+y,[1,2,3,4,5],[3,5,76,2]))) ##
# #################################################################
# #######################################################################################################################
#75.reduce函数,对参数序列中的元素进行积累 reduce(函数,[迭代序列])
#
# from functools import reduce
# def add(x,y):
# return x+y
#
# r=reduce(add,[1,2,34,4])
# print(r)
# #######################################################################################################################
# 76.filter函数,过滤函数 返回序列
#
from collections import *
# def isOdd(n):
# return n%2==1 # 余数为1
# def isOdd(n):
# if n%2==1:
# return n
#
# f=filter(isOdd,[1,2,3,45,6,7,8,432,1])
# print(list(f))
# #######################################################################################################################
# 77.enumerate函数,返回枚举对象函数,可迭代
#
# seasons=['dwe','qdw','dqq']
# print(list(enumerate(seasons)))
# #######################################################################################################################
# 78.zip函数,拉链函数 返回列表
#
# list1=[1,3,46,5]
# list2=['ss','ds','fr','qw']
# list3=[32,322,433,2322]
#
# ziped=zip(list1,list2,list3)
# print(list(ziped)) # [(1, 'ss', 32), (3, 'ds', 322), (46, 'fr', 433), (5, 'qw', 2322)]
# #######################################################################################################################
# 79.hasattr()判断一个对象是否有name属性和方法、
#*******************************************************************
# class function_demo(object): #*
# name='demo' # 属性(自身属性值) #*
# def run(self): # 方法(无参数) #*
# return "hello function" #*
# def run1(self,dog): # 函数(有参数) #*
# return "hello function "+dog #*
# #*
# functiondemo=function_demo() #*
# print(hasattr(functiondemo,'name')) #*
# print(hasattr(functiondemo, 'run')) #*
# print(hasattr(functiondemo, 'age')) #*
# print(functiondemo.run1('pig')) #*
# #*****************************************************************
# #######################################################################################################################
#getattr()获取对象属性和方法
# class function_demo(object):
# name='demo'
# def run(self):
# return "hello function"
#
# functiondemo=function_demo()
# print(getattr(functiondemo,'name')) # 返回姓名
# print(getattr(functiondemo, 'run')) # 返回地址
# #######################################################################################################################
#setattr()给对象属性进行赋值
# class function_demo(object):
# name='demo'
# def run(self):
# return "hello function"
#
# functiondemo=function_demo()
# print(hasattr(functiondemo,'name')) # 判断属性是否存在
# setattr(functiondemo,'age',18) # 属性赋值,相当于age=18
# print(hasattr(functiondemo, 'age')) # 判断属性是否存在
# #######################################################################################################################
# #######################################################################################################################
# 80.正则表达式//也称为规则表达式
# #######################################################################################################################
# 81.match函数
# match('匹配则正则表达式','要匹配的字符串',控制表达式匹配模式)
# import re
# m = re.match('www', 'Www.mobiletrain.org', re.I)
# if m != None:
# print(m.group()) # group和groups返回匹配结果, Www
# print(m.span()) # 匹配结果标志位 (0, 3)
# #######################################################################################################################
# 82.search函数
# import re
# print(re.search('www','www.taop.com')) # <_sre.SRE_Match object; span=(0, 3), match='www'>
# print(re.search('www','.wwwtam,mm.com')) # <_sre.SRE_Match object; span=(1, 4), match='www'>
# #######################################################################################################################
# 83.findall函数
# import re
# pattern=re.compile(r'\d+') # 查找数字
# result1=pattern.findall('' 'cwcww4422 fwwcfw2rrrc fc 34') # 查找数字
# result2=pattern.findall('cafev424rvevevd355cfcctfd5',0,10) # 查找数字
# print(result1)
# print(result2)
# #######################################################################################################################
# 84.finditer函数
# import re
# it=re.finditer(r'\d+','13ecwe5345fe52rwf4535vvwvc dcx32')
# for match in it:
# print(match.group())
# #######################################################################################################################
# 85.compile函数
#
import re
pattern=re.compile(r'\d+')
m=pattern.match('one12dcvkio230uiu9fkjfksm kfkl opi9i0')
print(m)
m=pattern.match('one12dcvkio230uiu9fkjfksm kfkl opi9i0',2,20)
print(m)
m=pattern.match('one12dcvkio230uiu9fkjfksm kfkl opi9i0',3,20)
print(m)
#print(m.groups())
print(m.group(0))
print(m.start(0))
print(m.end(0))
print(m.span(0))
# #######################################################################################################################
# 86.sub函数 re.sub(正则表达式模式,替换字符串,要被查找替换的原字符串,模式匹配后要替换的最大次数)
#
# import re
# phone='199-4629-0552' # gaagcec
#
# num1=re.sub(r'#.*$','',phone)
# print('电话号码:',num1)
#
# num2=re.sub('#.*$','',phone)
# print('电话号码:',num2)
#
# num3=re.sub(r'#','',phone)
# print('电话号码:',num3)
#
# num4=re.sub(r'\D+','',phone)
# print('电话号码:',num4)
#
# num5=re.sub(r'\D','',phone)
# print('电话号码:',num5)
#
# import re
#
# def double(matched):
# value=int(matched.group('value'))
# return str(value*2)
#
# s='a321mk3455kk523km'
# print(re.sub('(?P<value>\d+)',double,s))
# #######################################################################################################################
# 87.split函数
#
# import re
# print(re.split('\W+','lhrxxt,lhrxxt,lhrxxt.'))
# print(re.split('(\W+)','lhrxxt,lhrxxt,lhrxxt.'))
# print(re.split('\W+','lhrxxt,lhrxxt,lhrxxt.',1))
# print(re.split('a*','hello world!'))
Python文件及文件夹处理相关推荐
- Python监控目录文件夹,并使用SFTP上传目录及文件到linux服务器
Python 扫描监控本地文件夹并进行超大文件上传 方案1:WebUploader大文件分块多线程并发上传 方案2:watchdog目录文件夹监控,paramiko STFP上传服务器 方案3:优化2 ...
- python读取一个文件夹/子文件夹下的所有文件名字
python读取一个文件夹/子文件夹下的所有文件名字 示例代码: import osfile_path = './images/' all_file_name = os.listdir(file_pa ...
- Python递归获取文件夹下面所有文件名字:
Python递归获取文件夹下面所有文件名字: def getAllFiles(targetDir):files = []listFiles = os.listdir(targetDir)for i i ...
- python 检测文件或文件夹是否存在
python 检测文件或文件夹是否存在 文件 # 是否存在 import os os.path.exists(test_file.txt) # 是不是文件 import os os.path.isfi ...
- python自动整理文件夹_计算机文件和文件夹的Python自动管理,自动化,电脑,及
目录 一.输出目录所在的文件以及文件夹 import os print(os.getcwd())#获得当前文件的地址 print(os.path.join('MyProjects','AI'))#让P ...
- python删除空文件夹
python删除空文件夹 import glob import osdir_=r'G:\data\result'dirs=glob.glob(dir_+'/*/*')for dir in dirs:# ...
- Python的__pycache__文件夹
运行Python脚本时生成的__pycache__文件夹 原文:https://blog.csdn.net/index20001/article/details/73501375 用python编写好 ...
- python中shutil模块_python文件、文件夹、压缩包处理模块-shutil模块-阿里云开发者社区...
shutil模块 高级的文件.文件夹.压缩包 处理模块 本节内容基本在linux下python交互环境实现 复制移动文件.文件夹 将文件内容拷贝到另一个文件中,可以部分内容 格式如下: ``` shu ...
- python批量删除文件1001python批量删除文件_Python实现递归遍历文件夹并删除文件...
思路: 遍历文件夹下面的文件夹 如果文件夹名称等于".svn",则修改文件夹的属性(因为".svn"的文件都是只读的,你不能直接删除) 删除此文件夹 如果文件夹 ...
- python打开一个文件夹下所有txt文件-python读取一个目录下所有txt里面的内容方法...
实例如下所示: import os allFileNum = 0 def printPath(level, path): global allFileNum ''''' 打印一个目录下的所有文件夹和文 ...
最新文章
- 最牛逼的阿里巴巴内部Java调优方案,没有之一!
- Xamarin ios C#苹果应用开发第二讲配置环境和编写代码
- nginx下部署vue项目
- spring boot 整合redis实现方法缓存
- 一、为了OFFER系列 | 阿里云天池赛在线编程:移动的圆
- Spring Security在标准登录表单中添加一个额外的字段
- excel 汇总 mysql_利用mysql收集excel录入汇总
- java 判断是否包含中文_Java 判断字符串是否包含中文正则表达式
- Eclipse/NSight解决办法:unsolved inclusion stdio.h/map/string/queue/list
- 500状态码_教你玩转HTTP—状态码
- 微波工程基础_军工央企丨上海微波设备研究所
- 服务器 字体文件夹,服务器安装字体
- matlab-高数 反、双曲、正、余弦、正切函数
- 【公告】CSDN 博客将进行数据库维护
- Creating a Font for Apps and Games with Glyphs 如何使用Glyphs为应用和游戏创建字体 Lynda课程中文字幕
- MIT TR 35揭晓:阿里巴巴王刚、吴翰清等六位华人当选,Ian Goodfellow上榜
- 腾讯汤道生:面向数实融合新世界,开发者是最重要的“建筑师”
- 【tio-websocket】4、tio-websocket-server实现自定义集群模式
- ABAP学习----ALV注意事项
- 费曼、SQ3R、西蒙、 记忆、框架等学习法
热门文章
- Qt tableview
- 4 种最安全的 MacBook 电池更换选项
- 恶意进程 - 挖矿程序处理
- 利用JSP与JS实现简易购物车
- Android 屏幕刷新机制 VSync+Choreographer
- 稀疏矩阵——实现三元组,十字链表下的稀疏矩阵的加、转、乘的
- 21天学会c++(英汉对照,个人翻译,水平有限,供参考)-------第2天
- Surciata源码分析之IpsNFQ模式(1)
- 一图看懂:信号的时域、频域、相位 ​​​​
- 信息技术的技术趋势和未来展望