[Python] Python编程笔记

基础

数据结构

字符串
# ----- 查找
string.find(str, beg=0, end=len(string) )		#[0, len)中是否有str,有返回索引值,无返回-1
string.index(str, beg=0, end=len(string) )		#与find相同,但没有str回抛出异常
string.endswith(obj, beg=0, end=len(string) )	#[0, len)中是否以obj结尾,返回true,false
'am' in "I am GeoDoer"
dict

【dict】key-value对
1.key:key唯一;key不可变;可用数字、字符串或元组充当,但列表不行
2.value:任何值

# ----- 创建
d1.copy()		#浅复制
dict.fromkeys(seq [,val] )	#用seq做key创造新字典,可附加对应的val值
# ----- 删除
del d1["a"]	#删除"a"的条目
d1.clear()	#删除所有条目
del d1		#删除字典,删除后d不再存在,为unsubscriptable类型
# ----- 特点
len(d1)		#长度
str(d1)		#字符串打印
type(d1)==dict	#类型
# ----- 获得
d1.items()	#返回key-value的元组
d1.keys()	#返回所有键
d1.values()	#返回所有值
d1.get(key, default=None) #获得key的值,不存在则返回None
d1.setdefault(key, default=None)	#获得key的值,不存在则新填d1[key]=default的值
# ----- 操作
d1.pop(key [, default]) #删除key的值,返回value。不存在的话返回default
d1.popitem()			#返回并删除最后一对
d1.has_key(key)			#key在d1中,返回true
d1.update(d2)			#把d2更新到d1中
cmp(d1, d2)				#比较

输出

print("\r", '进度百分比:{}%'.format(i), end="", flush=True)	#print刷新
# tqdm
for img in tqdm(img_urls):
    save_file(img)
# 进度条库:progressbar

调用命令行

【当前线程调用】

# 【第一种】os.system
status = os.system("ipconfig") # 返回状态码
# 【第二种】os.popen
command_result = os.popen("python hello.py").readlines() #返回执行结果
# 【第三种】commands
status, output = commands.getstatusoutput('ipconfig') #获取状态、执行结果

【子线程调用】

sub=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
sub.wait()
print sub.read()

【运行多条命令】

cmd1 = "cd ../"
cmd2 = "python hw.py"
cmd = cmd1 + "&&" + cmd2

文件

路径
os.path.basename(path) 	#从全路径中解析文件名(含扩展名)
os.path.dirname(path) 	#从全路径中解析路径
os.path.splitext(path)[-1]	#从全路径中解析后缀名
os.listdir()			#列出文件夹下所有的文件与文件夹的名字
# glob
import glob
glob.glob(r'c:*.txt') 		# 列出C盘下所有txt文件
glob.glob(r'E:\pic**.jpg')  # 列出E盘下指定名字的文件
glob.glob(r'../*.py') 		# 相对路径
创建文件夹、复制移动文件
import shutil
import os
# 创建文件夹
def mkdir(path):
    path = path.strip()
    path = path.rstrip("\\")
    if not os.path.exists(path):
        os.makedirs(path)
        print( "[OK] Create Dir:{}".format(path) )
        return True
# 得到文件内容
def GetFileContext(fp):
    if not os.path.exists(fp): return None
    with open(fp, 'r', encoding="utf-8") as f:
        return f.read()
# 复制文件
def CopyFile(srcfile,dstfile):
    if not os.path.isfile(srcfile):
        print( "%s not exist!"%(srcfile) )
    else:
        fpath,fname=os.path.split(dstfile)
        if not os.path.exists(fpath):
            os.makedirs(fpath)
        shutil.copyfile(srcfile,dstfile)
        print( "copy %s -> %s"%(srcfile, dstfile) )
# 移动文件
def MoveFile(srcfile,dstfile):
    if not os.path.isfile(srcfile):
        print( "%s not exist!"%(srcfile) )
    else:
        fpath,fname=os.path.split(dstfile)
        if not os.path.exists(fpath):
            os.makedirs(fpath) 
        shutil.move(srcfile,dstfile)
        print("move %s -> %s"%( srcfile,dstfile) )
压缩
def DirToZip(dir, zip_fp, delete=False):
    ''' 文件夹打包成zip
    :param dir:     r'C:\data'
    :param zip_fp:  r'C:\data.zip'
    :param delete:  True 删除原文件(可选)
    :return:
    '''
    if not zip_fp.endswith('zip'): return None    #保存路径出错
    fps = []
    zipf = zipfile.ZipFile(zip_fp, "w") #创建一个zip对象
    for root,dirs,fns in os.walk(dir):
        for fn in fns:
            fp = os.path.join(root, fn)
            arcname = fp.replace(dir, '') #fn在dir中的相对位置
            zipf.write(fp, arcname)
            fps.append(fp)
    zipf.close()
    if delete:
        for fp in fps:
            os.remove(fp)
    return zip_fp
def FilesToZip(fps, zip_fp, delete=False):
    ''' 多文件打包成zip
    :param fps:   [r'C:\1.txt', r'C:\2.txt', r'C:\3.txt'] 文件全路径的list
    :param zip_fp:  r'C:\files.zip'
    :param delete:  True    删除原文件
    :return:
    '''
    if len(fps)==0: return None
    if not zip_fp.endswith("zip"): return None
    zipf = zipfile.ZipFile(zip_fp, "w") #在路径中创建一个zip对象
    for fp in fps:
        fn = os.path.basename(fp)
        zipf.write(fp, fn) #第一个参数为该文件的全路径;第二个参数为文件在zip中的相对路径
    zipf.close()    #关闭文件
    if delete:      #删除原文件
        for fp in fps:
            os.remove(fp)
    return zip_fp

GIS

shp
def ShpToGeoJOSN(shp_fp, json_fp=None):
    # shp文件转json
    if not shp_fp.endswith("shp"): return False

    if json_fp is None: json_fp = "{}.json".format( shp_fp[:-4] )
    elif not json_fp.endswith("json"): return False

    gdf = geopandas.read_file(shp_fp)
    gdf.to_file(json_fp, driver="GeoJSON", encoding="utf-8")
    return True
def GeoJSONToShp(json_fp, shp_fp=None):
    if not json_fp.endswith("json"): return False

    if shp_fp is None: shp_fp = "{}.shp".format( json_fp[:-5] )
    elif not shp_fp.endswith("shp"): return False

    gdf = geopandas.read_file(json_fp)
    gdf.to_file(shp_fp, encoding="utf-8")
    return True
def GetShpFiles(shp_path):
    formats = ["shp", "shx", "dbf", "prj", "sbn", "sbx", "cpg"]
    if not shp_path.endswith("shp"): return None
    shp_dir = os.path.dirname(shp_path)     #shp文件夹
    shp_name = os.path.basename(shp_path)   #shp文件名(包含扩展名)
    name = shp_name.replace('.shp', '')     #shp文件名(不包含扩展名)
    # 获得shp格式的所有文件
    fps = []
    for fn in os.listdir(shp_dir):
        ext = fn.split('.')[-1]
        if ext in formats and name in fn:
            fp = os.path.join(shp_dir, fn)
            fps.append(fp)
    return fps

常用

读写JSON
# 将obj保存到fp
def SaveJson(fp, obj):
    if os.path.exists(fp):
        os.remove(fp)
    with open(fp, 'w+') as f:
        json.dump(obj, f, indent=4)
        f.close()
    return fp
# 将对象从json文件中取出
obj = json.load(json_path)
Python2编码问题
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

geodoer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值