文件数目
list = [‘爱情买卖.mp3’,’阿凡达.mp4’]
files = range(len(list))
可以使用len(list)来计算list列表有多少个文件,这是为了帮助我们确定循环次数。
time
import time
print(‘当前时间 %s’ %(time.ctime()))
time.sleep(3)
print(‘当前时间 %s’ %(time.ctime()))
读写文件
f = open(“111.txt”,’a’)
f.write(‘讯飞集团\n’)
f.close()
with open(“111.txt”, ‘r’) as f1:
lines = f1.readlines()
print(lines)
apply (python2.*)
函数格式:apply(func,*args,**kwargs)
用途:当一个函数的参数存在于一个元组或者一个字典中时,用来间接的调用这个函数,并肩元组或者字典中的参数按照顺序传递给参数
解析:args是一个包含按照函数所需参数传递的位置参数的一个元组,是不是很拗口,意思就是,假如A函数的函数位置为 A(a=1,b=2),那么这个元组中就必须严格按照这个参数的位置顺序进行传递(a=3,b=4),而不能是(b=4,a=3)这样的顺序
kwargs是一个包含关键字参数的字典,而其中args如果不传递,kwargs需要传递,则必须在args的位置留空
apply的返回值就是函数func函数的返回值
'''python2.*
def function(a, b)
print(a,b)
apply(function,('good','better'))
apply(function,(2,3+6))
apply(function,('cai','quan'))
apply(function,('cai',),{'b':'caiquan'})
apply(function,(),{'a':'caiquan','b':'Tom'})
#--使用 apply 函数调用基类的构造函数
class Rectangle:
def __init__(self, color="white", width=10, height=10):
print "create a", color, self, "sized", width, "x", height
class RoundedRectangle(Rectangle):
def __init__(self, **kw):
apply(Rectangle.__init__, (self,), kw)
rect = Rectangle(color="green", height=100, width=100)
rect = RoundedRectangle(color="blue", height=20)
'''
输出结果:
输出结果:
('good', 'better')
(2, 9)
('cai', 'quan')
('cai', 'caiquan')
('caiquan', 'Tom')
create a green <__main__.Rectangle instance at 0x0678FA08> sized 100 x 100
create a blue <__main__.RoundedRectangle instance at 0x06620468> sized 10 x 20
注意:在python3.*apply()函数不再存在;必须使用星号标记。
采用最新命令法:
#1、
def run(self):
print ('staring', self.name, 'at:', ctime())
self.res=self.func() #python2中的用法,apply(self.func, self.args)
print( self.name, 'finished at:', ctime())
#2、
def run(self):
print ('staring', self.name, 'at:', ctime())
self.res=self.voice_tts() ##python2中的用法,apply(self.voice_tts,())的用法
print( self.name, 'finished at:', ctime())
#3、
apply(self.func, self.args) #python2中的用法
self.func(*self.args) #python3中的用法
利用当前时间、随机数产生唯一数字作为文件名:
'''python
#python3自动生成文件名
from datetime import *
import time
import random
for i in range(0,1):
nowTime = datetime.now().strftime("%Y%m%d%H%M%S")#生成当前的时间
randomNum = random.randint(0,100)#生成随机数n,其中0<=n<=100
if randomNum<=10:
randomNum = str(0) + str(randomNum)
uniqueNum = str(nowTime) + str(randomNum)
print(uniqueNum)
'''
或者
nowtime = time.strftime("%Y%m%d%H%M%S.%f", time.localtime(time.time()))
将Response转化为字典
import requests
url = 'http://127.0.0.1:5050/index'
def apiTestPost(url):
datas = {
'a':'cisco3',
'b':'cisco3'
}
r = requests.post(url,json=datas)
print r,type(r),r.text,type(r.text)
#取到响应数据r.text,为unicode的,需要转码
responseData = r.text.encode('utf-8')
#通过eval函数将字符串转换为字典
retdata = eval(responseData)
return retdata
以上用eval()将字符串转换为字典格式时会有中文编码问题,
解决方案替换为:
retdata = json.loads(responseData)
re = r.content.decode('utf-8')
python os 分离文件目录、文件名和文件后缀
import os
file_path = "D:/test/test.py"
(filepath,tempfilename) = os.path.split(file_path)
(filename,extension) = os.path.splitext(tempfilename)
其中:
filepath为文件的目录,即D:/test
filename为文件的名字,即test
extension为文件的扩展名,即.py
split()函数:
split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表。
os.path.split()函数:
os.path.split():将文件名和路径分割开。
#split()函数:
>>> s='hello python<[www.python.com]>hello python'
>>> s.split('[')[1].split(']')[0]
'www.python.com'
>>> s.split('[')[1].split(']')[0].split('.')
['www', 'python', 'com'
# os.path.split()函数:
>>> import os
>>> os.path.split('C:/soft/python/test.py')
('C:/soft/python', 'test.py')
>>> os.path.split('C:/soft/python/test')
('C:/soft/python', 'test')
>>> os.path.split('C:/soft/python/')
('C:/soft/python', '')
python 获取指定文件夹下所有文件名称并写入列表
import os
import os.path
rootdir = "./pic_data"
file_object = open('train_list.txt','w')
for parent,dirnames,filenames in os.walk(rootdir):
for filename in filenames:
print filename
file_object.write(filename+ '\n')
file_object.close()
在做深度学习的时候,会有大量的数据,为了方便,可以直接用命令拷贝到一个文件夹下
import shutil
import os
import os.path
rootdir = "./mjsynth/mnt/ramdisk/max/90kDICT32px"
#rootdir = "./123"
def Test2(rootDir):
for lists in os.listdir(rootDir):
#如果找到的是图片,则打印出来
if lists[-3:]=='jpg':
print lists
path = os.path.join(rootDir, lists)
shutil.copy(path,"./500")
continue
#如果找到的是文件夹,则判断,如果名称小于2则递归
if int(lists)<501:
path = os.path.join(rootDir, lists)
if os.path.isdir(path):
Test2(path)
Test2(rootdir)
遍历文件夹
rootdir = 'F:\data'
list = os.listdir(rootdir)#列出文件夹下所有的目录与文件
for i in range(0,len(list)):
path = os.path.join(rootdir,list[i])
if os.path.isfile(path):
#你想对文件的操作
python的os.path包含了很多文件、文件夹操作的方法:
os.path.abspath(path) #返回绝对路径
os.path.basename(path) #返回文件名
os.path.commonprefix(list) #返回多个路径中,所有path共有的最长的路径。
os.path.dirname(path) #返回文件路径
os.path.exists(path) #路径存在则返回True,路径损坏返回False
os.path.lexists #路径存在则返回True,路径损坏也返回True
os.path.expanduser(path) #把path中包含的"~"和"~user"转换成用户目录
os.path.expandvars(path) #根据环境变量的值替换path中包含的”$name”和”${name}”
os.path.getatime(path) #返回最后一次进入此path的时间。
os.path.getmtime(path) #返回在此path下最后一次修改的时间。
os.path.getctime(path) #返回path的大小
os.path.getsize(path) #返回文件大小,如果文件不存在就返回错误
os.path.isabs(path) #判断是否为绝对路径
os.path.isfile(path) #判断路径是否为文件
os.path.isdir(path) #判断路径是否为目录
os.path.islink(path) #判断路径是否为链接
os.path.ismount(path) #判断路径是否为挂载点()
os.path.join(path1[, path2[, ...]]) #把目录和文件名合成一个路径
os.path.normcase(path) #转换path的大小写和斜杠
os.path.normpath(path) #规范path字符串形式
os.path.realpath(path) #返回path的真实路径
os.path.relpath(path[, start]) #从start开始计算相对路径
os.path.samefile(path1, path2) #判断目录或文件是否相同
os.path.sameopenfile(fp1, fp2) #判断fp1和fp2是否指向同一文件
os.path.samestat(stat1, stat2) #判断stat tuple stat1和stat2是否指向同一个文件
os.path.split(path) #把路径分割成dirname和basename,返回一个元组
os.path.splitdrive(path) #一般用在windows下,返回驱动器名和路径组成的元组
os.path.splitext(path) #分割路径,返回路径名和文件扩展名的元组
os.path.splitunc(path) #把路径分割为加载点与文件
os.path.walk(path, visit, arg) #遍历path,进入每个目录都调用visit函数,visit函数必须有3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有文件名,args则为walk的第三个参数
os.path.supports_unicode_filenames #设置是否支持unicode路径名
python创建文件夹,清空文件夹
filepath = ".\\audio_vad_file\\"
os.makedirs(filepath) #创建一个文件夹
shutil.rmtree("audio_vad_file") #将整个文件夹删除
os.mkdir(filepath) #重新创建文件夹
python 获取目录下最新的一个文件
'''获取最新的单个文件'''
def new_report(test_report):
lists = os.listdir(test_report) #列出目录的下所有文件和文件夹保存到lists
print(list)
lists.sort(key=lambda fn:os.path.getmtime(test_report + "\\" + fn))#按时间排序
file_new = os.path.join(test_report,lists[-1]) #获取最新的文件保存到file_new
print(file_new)
return file_new
if __name__=="__main__":
test_report="path"#目录地址
new_report(test_report)
python 实现定时遍历目录,每次把目录下的最新的文件放到列表里
import os
import time
import shutil
'''将文件夹中新生成的文件标记,从而进行识别'''
def getFileListType(path, deal_type_dict):
'定时每分钟调用此函数'
file_list = os.listdir(path)
for file in file_list:
# 判断是否是新进来的文件
if file not in deal_type_dict:
deal_type_dict[file] = 0 # 0表示文件未下一步操作,1表示已处理
continue
print("结束标记")
def main():
# 初始化切割文件夹
vad_filepath = ".\\audio_vad_file\\"
#os.makedirs(vad_filepath) # 创建一个文件夹
shutil.rmtree("audio_vad_file") # 将整个文件夹删除
os.mkdir(vad_filepath) # 重新创建文件夹
deal_type_dict = {}
while True:
try:
audio_vad_file = ".\\audio_vad_file\\"
getFileListType(audio_vad_file, deal_type_dict)
print(deal_type_dict)
time.sleep(10)
for deal_file in deal_type_dict:
if deal_type_dict[deal_file] == 0:
# deal_next_function(deal_file) # 新文件处理操作
print("新文件经过处理")
deal_type_dict[deal_file] = 1 # 并标识处理过的文件
continue
print(deal_type_dict)
print("标记及处理完毕")
except:
print("出错了")
break