1.复制文件或者文件夹
- 复制某个目录下面的文件到另一个目录下面。
源文件和目标文件都只能是文件,且目标文件必须存在(open file not mknod),且有权限写入:shutil.copyfile(source_file_path,target_file_path)
def copy_file_cp_unix():
source_path = 'source_file/test.py'
source_path=os.path.join(os.getcwd(),source_path)
target=os.path.join(os.getcwd(),"target_file")
target=os.path.join(target,os.path.basename(source_path))
print(target)
# create the folders if not already exists
if not os.path.exists(target):
#MacOS需要超级用户权限才能运行mknod。如果您不想升级权限来创建文件,可以改为这样做
open(target, 'w').close()
# adding exception handling
try:
shutil.copyfile(source_path, target)
except IOError as e:
print("Unable to copy file. %s" % e)
except:
print("Unexpected error:", sys.exc_info())
- 复制文件夹到某个目录下面
复制某个文件夹到另一个目录下面,复制后的结果目录为“目录/某个文件夹“,注意这个复制后的结果目录在复制前必须是不存在的。
def copy_files():
source_base_name = 'source_file'
source_dir = os.path.join(os.getcwd(), source_base_name)
target_dir = os.path.join(os.getcwd(), "target_file_path")
target_dir=os.path.join(target_dir,source_base_name)
# 如果目录存在,删除单层目录。
if os.path.exists(target_dir):
os.rmdir(target_dir)
# adding exception handling
try:
shutil.copytree(source_dir, target_dir)
except IOError as e:
print("Unable to copy file. %s" % e)
except:
print("Unexpected error:", sys.exc_info())
2.删除文件和强制删除有内容的文件
remove(path)
#删除文件
rmdir(path)
#删除单层目录,如该目录非空则抛出异常
removedirs(path)
#递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常
def delete_files():
source_base_name = 'source_file'
target_dir = os.path.join(os.getcwd(), "target_file_path")
target_dir = os.path.join(target_dir, source_base_name)
if os.path.exists(target_dir):
shutil.rmtree(target_dir)
3.判断目录是否存在
def file_exists(target_file_or_dir):
if os.path.exists(target_file_or_dir):
return True
return False
4.创建文件目录
mkdir(path)
创建单层目录,如该目录已存在抛出异常
makedirs(path)
递归创建多层目录,如该目录已存在抛出异常,注意:'E:\a\b’和’E:\a\c’并不会冲突
创建的目录
5.打印某个目录下面的所有文件
os.listdir(path)返回的是一个包含该目录下面的所有文件的文件名的字符串的列表。
#获取一个目录下所有文件的个数
allFileNum = 0
def printPath(level, path):
global allFileNum
'''
打印一个目录下的所有文件夹和文件
'''
# 所有文件夹,第一个字段是次目录的级别
dirList = []
# 所有文件
fileList = []
# 返回一个列表,其中包含在目录条目的名称(google翻译)
files = os.listdir(path)
# 先添加目录级别
dirList.append(str(level))
for f in files:
if(os.path.isdir(path + '/' + f)):
# 排除隐藏文件夹。因为隐藏文件夹过多
if(f[0] == '.'):
pass
else:
# 添加非隐藏文件夹
dirList.append(f)
if(os.path.isfile(path + '/' + f)):
# 添加文件
fileList.append(f)
# 当一个标志使用,文件夹列表第一个级别不打印
i_dl = 0
for dl in dirList:
if(i_dl == 0):
i_dl = i_dl + 1
else:
# 打印至控制台,不是第一个的目录
print('-' * (int(dirList[0])), dl)
# 打印目录下的所有文件夹和文件,目录级别+1
printPath((int(dirList[0]) + 1), path + '/' + dl)
for fl in fileList:
# 打印文件
print('-' * (int(dirList[0])), fl)
# 随便计算一下有多少个文件
allFileNum = allFileNum + 1
6.借助mmap映射快速获取某个文件的所有行数
def get_file_row_count_mmap(dataPath):
start = time.time()
with open(dataPath, "r") as f:
# memory-map the file, size 0 means whole file
map = mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ)
count = 0
while map.readline():
count += 1
print(count)
map.close()
print(time.time() - start)
#https: // blog.youkuaiyun.com / weixin_36060412 / article / details / 112521082
return count
7.获取某一个文件的最后一行
# 文件已经生成后,取得文件的最后一行。
def get_last_row(self, file_name):
with open(file_name, 'rb') as f: # 打开文件
# 在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始,只能seek(offset,0)
first_line = f.readline() # 取第一行
offset = -50 # 设置偏移量
while True:
"""
file.seek(off, whence=0):从文件中移动off个操作标记(文件指针),正往结束方向移动,负往开始方向移动。
如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。
"""
f.seek(offset, 2) # seek(offset, 2)表示文件指针:从文件末尾(2)开始向前50个字符(-50)
lines = f.readlines() # 读取文件指针范围内所有行
if len(lines) >= 2: # 判断是否最后至少有两行,这样保证了最后一行是完整的
last_line = lines[-1] # 取最后一行
break
# 如果off为50时得到的readlines只有一行内容,那么不能保证最后一行是完整的
# 所以off翻倍重新运行,直到readlines不止一行
offset *= 2
print('文件' + file_name + '第一行为:' + first_line.decode())
print('文件' + file_name + '最后一行为:' + last_line.decode())
return last_line.decode()
8.重命名文件
def rename_file(old, new):
os.rename(old, new)
9.其余链接
python读写、创建文件、文件夹等等_python学习者的博客-优快云博客_python 新建文件夹
学习笔记、os模块函数、exists、isabs、isdir、islink、samefile_iken_g的博客-优快云博客