最近发现的一些Python写程序的小技巧

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Grace_0642/article/details/81564624

巧妙的使用enumerate 可以得到元素和序列号。

In [1]: n_topics = range(1,50,2)

In [2]: for idx, n_topic in enumerate(n_topics):
   ...:     print idx,n_topic
   ...:   

得到的输出如下所示:

0 1
1 3
2 5
3 7
4 9
5 11
6 13
7 15
8 17
9 19
10 21
11 23
12 25
13 27
14 29
15 31
16 33
17 35
18 37
19 39
20 41
21 43
22 45
23 47
24 49

写文件的追加和C语言是不同的,就是单纯的a 对于w+ 这个和w的效果是一样的。如果文件存在那么我们用这个语句

f = open(filepath,"w+")
f = open(filePath, "w")

效果都是一样的,都是没有文件的话会自动创建,然后覆盖之前的文件的内容。

要追加的话直接用

f = open(filePath,"a")



这里写图片描述

猜你喜欢

转载自blog.csdn.net/Grace_0642/article/details/81564624