python3之文件操作
import osimport shutilimport time# 格式化时间def formatTime(longtime):return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(longtime))# 获取文件大小,结果保留两位小数,单位MBdef get_file_size(path):f = ...
·
import os
import shutil
import time
# 格式化时间
def formatTime(longtime):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(longtime))
# 获取文件大小,结果保留两位小数,单位MB
def get_file_size(path):
f = os.path.getsize(path)
f = f/float(1024 * 1024)
return round(f, 2)
# 复制一个文件夹下的文件到另一个文件夹
def copyfilesbetweendirs(srcPath, dstPath):
if not os.path.exists(srcPath):
print('srcPath dose not exist.')
return
if os.path.exists(dstPath):
try:
shutil.rmtree(dstPath)
except Exception as e:
print(e)
for fileobj in os.listdir(srcPath):
#print(fileobj)
if os.path.isdir(fileobj):
try:
shutil.copytree(os.path.join(srcPath, fileobj), os.path.join(dstPath, fileobj))
except Exception as e:
print(e)
elif os.path.isfile(fileobj):
try:
shutil.copyfile(os.path.join(srcPath, fileobj), os.path.join(dstPath, fileobj))
except Exception as e:
print(e)
return
# 显示一个目录下所有文件和文件夹的最后修改时间
def showfileinfo(filePath):
if not os.path.exists(filePath):
print('filePath does not exist.')
return
for fileobj in os.listdir(filePath):
fileinfo = os.path.getmtime(os.path.join(filePath, fileobj))
if os.path.isdir(fileobj):
print(fileobj, formatTime(fileinfo))
elif os.path.isfile(fileobj):
print(fileobj, formatTime(fileinfo))
if __name__ == '__main__':
copyfilesbetweendirs('E:\\PythonDataScience','E:\\bat_learning')
showfileinfo('E:\\bat_learning')
更多推荐
所有评论(0)