Skip to content

Instantly share code, notes, and snippets.

@iguoli
Last active November 30, 2017 12:33
Show Gist options
  • Save iguoli/e62727a6c140ff4393467643bb1db1e0 to your computer and use it in GitHub Desktop.
Save iguoli/e62727a6c140ff4393467643bb1db1e0 to your computer and use it in GitHub Desktop.
Python常用功能代码段

从命令行读取多个文件名,支持'*'作为通配符

import sys
from glob import glob

if len(sys.argv) >= 2:
    filelist = []
    for f in sys.argv[1:]:
        filelist.extend(glob(f))
    print(filelist)

    for f in filelist:
        # 将文件名传入你的处理函数
        process_func(f)
else:
    sys.exit('需要指定一个或多个文件名')

读取文件的文件名和扩展名

import os

f = "a/b/c/d.txt"
name, ext = os.path.splitext(f)
print(name, ext)
print(os.path.dirname(f))
print(os.path.basename(f))

输出结果

a/b/c/d .txt
a/b/c
d.txt

写文件

with open('a.txt', 'r') as f, open('b.txt', 'a') as out:
    for line in f:
        print(line)
    out.write('You’re still goin’ strong\n')

对列表去重,再按原顺序排序

ids = [1,4,3,3,4,2,3,4,5,6,1]
new_ids = list(set(ids))
new_ids.sort(key=ids.index)

判断变量是否为函数

hasattr(f, '__call__')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment