码修
2020 年 2 月 26 日
1 获取文件名列表
- import os
- names = os.listdir('somedir')
如果要查找特定后缀名文件, 你可能会考虑使用 glob 或 fnmatch 模块. 比如:
- import glob
- pyfiles = glob.glob('somedir/*.py')
- from fnmatch import fnmatch
- pyfiles = [name for name in os.listdir('somedir')
- if fnmatch(name, '*.py')]
refs:5.13 获取文件夹中的文件列表 - python3-cookbook 3.0.0 文档
2 修改文件名后缀
- import os
- thisFile = "mysequence.fasta"
- base = os.path.splitext(thisFile)[0]
- os.rename(thisFile, base + ".aln")
或者
- from pathlib import Path
- p = Path('mysequence.fasta')
- p.rename(p.with_suffix('.aln'))
- refs: rename - Changing file extension in Python - Stack Overflow
3 判断字符串是否包含子串
[5 种方法] Python 判断字符串是否包含子串 - 码中人
4 简易爬虫
- resource = urllib.request.urlopen(an_url)
- content = resource.read().decode(resource.headers.get_content_charset())
5 删除多层目录下多个文件
- import os
- import glob
- files = glob.glob('/tmp/**/*.txt', recursive=True)
- for f in files:
- try:
- os.remove(f)
- except OSError as e:
- print("Error: %s : %s" % (f, e.strerror))
来源: http://www.mzh.ren/python-code-snippets.html