以写的方式打开文件
In [1]: fd=open('/tmp/1.txt','w')
In [2]: fd
Out[2]: <_io.TextIOWrapper name='/tmp/1.txt' mode='w' encoding='UTF-8'>
In [3]: fd.buffer
fd.buffer fd.errors fd.mode fd.readline
fd.close fd.fileno fd.name fd.readlines
fd.closed fd.flush fd.newlines fd.seek >
fd.detach fd.isatty fd.read fd.seekable
fd.encoding fd.line_buffering fd.readable fd.tell
写数据进入文件
In [3]: fd.write('123\n')
Out[3]: 4
In [4]: quit
[root@localhost tmp]# cat 1.txt
123
默认以读的方式打开文件
In [1]: fd=open('/tmp/1.txt')
读出文件内容
In [2]: fd.read()
Out[2]: '123\n'
追加的方式写入文件
In [8]: fd=open('/tmp/1.txt','a')
In [9]: fd.write('789\n')
Out[9]: 4
In [10]: fd=open('/tmp/1.txt')
In [11]: fd.read()
Out[11]: '456\n789\n'
一行一行的读取数据
In [27]: fd.readlines()
Out[27]: ['456\n', '789\n']
编写一个读文件的python脚本
#! /bin/python
fd =open('/tmp/1.txt')
for line in fd.readlines():
print(line,end="")
[root@localhost studypy]# python3 test_1123_1.py
456
789
优化的写法
#! /bin/python
fd =open('/tmp/1.txt')
for line in fd:
print(line,end="")
while遍历文件
#! /bin/python
fd = open('/tmp/1.txt')
while True:
line = fd.readline()
if not line:
break
print(line,end="")
[root@localhost studypy]# python3 test_1123_2.py
456
789
with open的使用
#! /bin/python
with open('/tmp/1.txt') as fd:
while True:
line = fd.readline()
if not line:
break
print(line,end="")
统计服务器的内存
#! /bin/python
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
total=line.split()[1]
if line.startswith('MemFree'):
free=line.split()[1]
print("total is %d M,free is %d M."%(int(total)/1024,int(free)/1024))
数值类型转换
十六进制和十进制
In [10]: int('0xa',16)
Out[10]: 10
In [11]: hex(10)
Out[11]: '0xa'