Python的一些小知识点_4


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()
参考链接:

如何使用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)

参考链接:

在Linux下查看所有打开的文件——用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中的正则表达式
参考链接:
(?:...)
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中合并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

参考链接:
另,将嵌套列表转换成一维列表的方法:
,

《“Python的一些小知识点_4”》 有 1 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注