python-file

utf8

注意跳过开头 3 个字节的 BOM

with codecs.open(filePath, 'r+', 'utf-8') as f:
content = f.read()
f.seek(3, 0)
f.write(statisticStr + content)

delete

os.remove() removes a file.
os.rmdir() removes an empty directory.
shutil.rmtree() deletes a directory and all its contents.

current path

os.path.exists(test_file.txt)
#True

是否存在

if not os.path.exists('./logs'):
os.makedirs('./logs')

os.path.exists(test_file.txt)
#True

# 这个接口可能会误判 同名文件夹 为 文件
os.path.isfile("test-data")
#True

遍历

import os
for root, dirs, files in os.walk(".", topdown=True):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))

# 排序 文件名是:‘ori_data0.txt’
files.sort(key=lambda x: int(x.split('.')[0][8:]))

读写文件

# Python code to 
# demonstrate readlines()

L = ["Geeks\n", "for\n", "Geeks\n"]

# writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()

# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()

# read line without '\n'
open("file.txt").read().splitlines()
['a', 'b', 'c', 'd']

count = 0
# Strips the newline character
for line in Lines:
print("Line{}: {}".format(count, line.strip()))

path split

path = 'C:\\Program Files (x86)\\SPC\\Release\\Bin\\MeasureChartData\\P9.txt'
os.path.split(path)
# tuple 'C:\\Program Files (x86)\\SPC\\Release\\Bin\\MeasureChartData' 'P9.txt'

复制文件

try:
shutil.copyfile(filePath, copy_path)
except IOError as e:
import traceback
traceback.print_exc()
errMsg = traceback.format_exc()
log.info(f"Unable to copy file. {errMsg}")
except:
import traceback
traceback.print_exc()
errMsg = traceback.format_exc()
log.info(f"Unexpected copy file error:{errMsg}")

创建目录

import os
def mkdir(path):
# 去除首位空格
path=path.strip()
# 去除尾部 \ 符号
path=path.rstrip("\\")
# 判断路径是否存在
isExists=os.path.exists(path)
# 判断结果
if not isExists:
# 如果不存在则创建目录,创建目录操作函数
'''
os.mkdir(path)与os.makedirs(path)的区别是,当父目录不存在的时候os.mkdir(path)不会创建,os.makedirs(path)则会创建父目录
'''
#此处路径最好使用utf-8解码,否则在磁盘中可能会出现乱码的情况
os.makedirs(path.decode('utf-8'))
print path+' 创建成功'
return True
else:
# 如果目录存在则不创建,并提示目录已存在
print path+' 目录已存在'
return False
# 定义要创建的目录
path=r"d:\\web天下\\"
# 调用函数
mkdir(path)

删除目录

# 只能删除空目录
os.rmdir(“dir”)
# 空目录、有内容的目录都可以删
shutil.rmtree(“dir”)