Python打开文件的最佳实践
带有try的open()方法:
file = open("/tmp/foo.txt") try: data = file.read() finally: file.close()
简洁明快的with语句:
with open("/tmp/foo.txt") as file: data = file.read()
参考链接:
- http://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement
- 理解Python的With语句- linbo
- python with用法
如何使用Python判断一个文件是否存在?
You can use: import os os.path.isfile(fname) if you need to be sure it's a file. ==== You have the os.path.exists function: import os.path os.path.exists(file_path) This returns True for both files and directories. Use os.path.isfile to test if it's a file specifically. ==== Unlike isfile(), exists() will yield True for directories. So depending on if you want only plain files or also directories, you'll use isfile() or exists(). >>> print os.path.isfile("/etc/passwd") True >>> print os.path.isfile("/etc") False >>> print os.path.isfile("/does/not/exist") False >>> print os.path.exists("/etc/passwd") True >>> print os.path.exists("/etc") True >>> print os.path.exists("/does/not/exist") False
即:
import os
os.path.isfile(fname)
参考链接:
- http://stackoverflow.com/questions/82831/check-if-a-file-exists-using-python
- http://stackoverflow.com/questions/8933237/how-to-find-if-directory-exists-in-python
在Linux下查看所有打开的文件——用Python实现
参考链接:
- http://search.aol.com/aol/search?q=linux+use+python+implement+lsof
- https://pypi.python.org/pypi/psutil
- http://stackoverflow.com/questions/20106220/check-for-open-files-with-python-in-linux
- http://stackoverflow.com/questions/11114492/check-if-a-file-is-not-open-not-used-by-other-process-in-python
- http://stackoverflow.com/questions/2023608/check-what-files-are-open-in-python
Python的split()方法
str.split([sep[, maxsplit]]) Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,'1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1','2', '3']). Splitting an empty string with a specified separator returns ['']. If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns []. For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].
测试用例:
ttt = ''' GET http://justin.ixyzero.com/app/styles/justin.css HTTP/1.1 Accept: text/css, */* Content-Type: text/css =====12345===== Content-Type: text/css Content-Type: text/css =====12345===== Content-Type: text/css Content-Type: text/css Content-Type: text/css''' find_str = ttt.split('=====12345=====') find_str = ttt.split('=====12345=====', 1)
参考链接:
https://docs.python.org/2/library/stdtypes.html#str.split
Python中的正则表达式
参考链接:
- https://docs.python.org/2/howto/regex.html
- https://docs.python.org/2/library/re.html
- Python正则表达式指南
使用 Python 的re模块
正则表达式30分钟入门教程 #非捕获
(?:...) A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.
还有就是注意:
search() / match() 的不同:match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况,而 search() 函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用 search();
findall() / finditer() 的不同。
在Python中检测list是否为空的最佳方式
#Using the implicit booleanness of the empty list is quite pythonic. if not a: print "List is empty" #### The pythonic way to do it is from the style guide[ http://www.python.org/dev/peps/pep-0008/ ]: For sequences, (strings, lists, tuples), use the fact that empty sequences are false. Yes: if seq: if not seq: No: if len(seq): if not len(seq): #### if len(seq) == 0: print 'the list is empty' #### An empty list is itself considered false in true value testing (see https://docs.python.org/2/library/stdtypes.html#truth-value-testing): a = [] if a: print "not empty"
参考链接:
- python – Best way to check if a list is empty
- https://docs.python.org/2/library/stdtypes.html#truth-value-testing
- http://www.python.org/dev/peps/pep-0008/
在Python中合并list的最佳方式
搜索关键字:http://cn.bing.com/search?q=python+merge+two+list+efficient
What is the most efficient way to concatenate two lists list_a and list_b when: list_b items have to be placed before list_a items the result must be placed in list_a I have 4 possibilities in mind: # 1 list_a = list_b + list_a # 2 for item in list_b: list_a.insert(0, item) # 3 for item in self.list_a: list_b.append(item) list_a = list_b # 4 list_a[0:0] = list_b Thanks!
即,为了简单起见,推荐使用第一种方式:
list_a = list_b + list_a
参考链接:
- http://stackoverflow.com/questions/12088089/python-list-concatenation-efficiency #Python中各种list合并方法的效率对比
- http://stackoverflow.com/questions/11574195/how-to-merge-multiple-lists-into-one-list-in-python
- http://stackoverflow.com/questions/1720421/merge-two-lists-in-python
- http://stackoverflow.com/questions/22642261/python-concatenate-2-lists
另,将嵌套列表转换成一维列表的方法:
- http://stackoverflow.com/questions/8327856/how-to-extract-nested-lists
- http://stackoverflow.com/questions/3046217/join-a-list-of-lists-together-into-one-list-in-python
- http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
- http://stackoverflow.com/questions/10823877/what-is-the-fastest-way-to-flatten-arbitrarily-nested-lists-in-python
- http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python
《“Python的一些小知识点_4”》 有 1 条评论
[译]Python正则表达式拾珠
http://frostming.win/2018/02-06/python-hidden-regexp
http://lucumr.pocoo.org/2015/11/18/pythons-hidden-re-gems/