for循环

1
2
3
4
5
for i in range(5):
print(i)
i += 1
# output
1 2 3 4 5

for 循环中的 循环变量 不会被修改,此时应使用 while。

with表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
with open('output/0.txt') as f1:
# 这里的f2是动态变化的
f2 = open('output/2.txt')
# f2.close()

print(f2.readline())
print(f1.readline())

# output
2016-03-22 20:25:28,20001,89,NQ,396,58.00,S

Traceback (most recent call last):
File "D:/0hadoop/python/pystudy/action/test.py", line 7, in <module>

print(f1.readline())
ValueError: I/O operation on closed file.

with表达式建立的上下文会自动关闭IO。

列表

1
2
3
l = []
# return None,不应该作为参数,应该 fun(l + ["sth"])
l.append("sth")

%

1
2
# 7
print(-123%10)
1
2
// -3
System.out.println(-123%10)

Python IO

读text data

1
2
3
4
5
6
7
# 读整个文件为一个字符串
with open('somefile.txt') as f:
data=f.read()

#迭代处理文件
with open('somefile.txt') as f:
for line in f:

写text data,会覆盖。

1
2
3
4
5
6
7
8
with open('somefile.txt') as f:
f.write(text1)
f.write(text2)

with open('somefile.txt') as f:
#输出重定向到f,覆盖
print(line1,file=f)
print(line2,file=f)

追加文本文件,open(… , ‘at’)

binary data

such as images、sound files等等。

Infinite

如果只需要一个表示无限的数,可以用:

1
2
float('inf')
float('-inf')

全局变量不要命名太简单,例如 i,j;否则容易与局部变量冲突。