讲解python目录及文件操作实例代码


把原文件夹下的文件复制到另一个文件夹,并且更改文件名,随机的新文件名,并把新旧文件名一起写入一个文件内.

#encoding=utf-8
import os,time,shutil,random
#读取目录,生成新的文件目录

DocumentName = whx/
OpPath = D:/pydir/ishoe8/

fileList = os.listdir(OpPath DocumentName)
sWrite = []
for fileName in fileList:
 print(fileName)
 tmptt = str(time.time()).split(.)
 newFileName = tmptt[0] tmptt[1] str(random.randint(100000,999999))
 fileType = fileName.split(.)
 newFileName = . fileType[1]
 print(newFileName)
 sWrite.append(fileName , newFileName)
 if not os.path.isdir( OpPath new/ DocumentName ) :
  os.mkdir(OpPath new/ DocumentName)
 shutil.copyfile(OpPath DocumentName fileName,OpPath new/ DocumentName newFileName)

#写进文件
sWrite = " ".join(sWrite)
filehandler = open(OpPath new/ DocumentName list.txt,w)               #以写模式打开文件,如果文件不存在则创建
filehandler.write(sWrite)
filehandler.close()

相关内容

    暂无相关文章

评论关闭