[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
文件的处理1
In [5]: f = open('/etc/hosts') #打开
In [6]: data = f.read() #处理
In [7]: print data,
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
In [8]: f.close() #关闭
文件的处理2
In [9]: f = open("/etc/hosts")
In [10]: for line in f:
....: print line,
....:
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
In [11]: f.close()
以写的方式打开,文件如果不存在就创建,文件存在就先清空。
In [12]: f = open('hi.txt','w')
In [13]: f.write('hello world!\n')
In [14]: f.writelines(['2nd line. \n','3nd line. \n'])
In [15]: f.close()
[root@ftp ~]# cat hi.txt
hello world!
2nd line.
3nd line.
文件复制
[root@ftp day03]# vi cp.py
1 #!/usr/bin/env python
2
3 sfname = '/bin/ls'
4 dfname = '/root/ls'
5 src_fobj = open(sfname)
6 dst_fobj = open(dfname,'w')
7
8 while True:
9 data = src_fobj.read(4096)
10 if not data:
11 break
12 dst_fobj.write(data)
13
14 src_fobj.close()
15 dst_fobj.close()
执行结果:
[root@ftp day03]# python cp.py
[root@ftp day03]# ls /root/ls
/root/ls
MD5值一样,证明复制没有问题
[root@ftp day03]# md5sum /bin/ls /root/ls
8fb280d1b85be20203b57e9980d568c1 /bin/ls
8fb280d1b85be20203b57e9980d568c1 /root/ls
#计算内存大小
[root@weblamp ~]# vi test.py
#!/usr/bin/python
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
total = line.split()[1]
continue
if line.startswith('MemFree'):
free =line.split()[1]
break
print "%.2f" % (int(free)/1024.0) + 'M'
~
~
"test.py" 10L, 301C written
[root@weblamp ~]# python test.py
332.52M
#计算MAC地址
[root@weblamp ~]# vi mac.py
#!/usr/bin/env python
macaddr = '00:0C:29:D1:6F:0a'
prefix_mac = macaddr[:-3]
last_two = macaddr[-2:]
plus_one = int(last_two,16) + 1
if plus_one in range(10):
new_last_two = hex(plus_one)[2:]
new_last_two = '0' + new_last_two
else:
new_last_two = hex(plus_one)[2:]
if len(new_last_two)==1:
new_last_two = '0' + new_last_two
new_mac = prefix_mac + ':' + new_last_two
print new_mac.upper()
~
"mac.py" [New] 15L, 414C written
[root@weblamp ~]# python mac.py
00:0C:29:D1:6F:0B