2、不用if len(somelist) == 0来检查空值,而用if not somelist来检查(它会假定:空值将自动评估为False)。
3、检测是否为非空值时,用if somelist会默认把非空值判断为True
4、引入模块的时候,总是应该使用绝对名称,而不应该根据当前模块的路径来使用相对名称。例如,引入bar包中的foo模块时,应该完整写出from bar import foo。如果一定要用相对名称来编写import语句,那就采用明确的写法:from.import foo。import语句按顺序分三部分,分别代表标准库模块、第三方模块及自用模块,在每一部分中,各import语句应该按模块的字母顺序来排序。
5、实现接受str或unicode,并总返回unicode:
1 2 3 4 5 6
defto_unicode(unicode_or_str): if isinstance(unicode_or_str,str): value = unicode_or_str.decode('utf-8') else: value = unicode_or_str return value
6、实现接受str或unicode,并总返回str
1 2 3 4 5 6
defto_str(unicode_or_str): if isinstance(unicode_or_str,unicode): value = unicode_or_str.encode('utf-8') else: value = unicode_or_str return
7、用列表推导来取代map和fileter
8、合并pdf
1 2 3 4 5 6 7 8
import os from PyPDF2 import PdfFileReader,PdfFileMerger files_dir = 'e:\\pdf' pdf_files = [f for f in os.listdir(files_dir) if f.endswith('pdf')] merger = PdfFileMerger() for filename in pdf_files: merger.appedn(PdfFileReader(os.path.join(file_dir,filename),'rb')) merger.writer(os.path.join(files_dir,'merged_full.pdf'))