文件处理

打开文件的方法

r: 以读方式打开 
w: 以写方式打开 
a: 以追加模式打开 
r+: 以读写模式打开 
w+: 以读写模式打开 
a+: 以读写模式打开 
rb: 以二进制读模式打开 
wb: 以二进制写模式打开 
ab: 以二进制追加模式打开 
rb+: 以二进制读写模式打开 
wb+: 以二进制读写模式打开 
ab+: 以二进制读写模式打开
  • 注意 
    以w打开文件会覆盖原来的文件

读取文件的方法

In [31]: fd.
             fd.close      fd.errors     fd.isatty     fd.newlines   fd.readinto   fd.seek       fd.truncate   fd.xreadlines 
             fd.closed     fd.fileno     fd.mode       fd.next       fd.readline   fd.softspace  fd.write                    
             fd.encoding   fd.flush      fd.name       fd.read       fd.readlines  fd.tell       fd.writelines               
In [30]: fd = open('/tmp/tmp.txt')

In [31]: fd.read()
Out[31]: '1
2
3
'

In [32]: fd = open('/tmp/tmp.txt')

In [33]: fd.readline()
Out[33]: '1
'

In [34]: fd.readline()
Out[34]: '2
'

In [35]: fd.readline()
Out[35]: '3
'

In [36]: fd.readline()
Out[36]: ''

In [37]: fd = open('/tmp/tmp.txt')

In [38]: fd.readlines()
Out[38]: ['1
', '2
', '3
']

In [39]: fd.readlines()
Out[39]: []

In [40]: fd = open('/tmp/tmp.txt')

In [41]: fd.next()
Out[41]: '1
'

In [42]: fd.next()
Out[42]: '2
'

In [43]: fd.next()
Out[43]: '3
'

In [44]: fd.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-44-3df4eef70a28> in <module>()
----> 1 fd.next()

  

小结

fd.read():返回的是字符串
fd.readline():返回的是每一行字符串
fd.readlines():返回的是一行列表

for遍历文件的方法

[root@wangtian day02]# cat /tmp/tmp.txt
1
2
3
[root@wangtian day02]# cat 14.py 
#!/usr/bin/python
fd = open('/tmp/tmp.txt')
for line in fd.readlines():
    print line,
[root@wangtian day02]# python 14.py 
1
2
3
[root@wangtian day02]# cat 14.py > 15.py
[root@wangtian day02]# vi 15.py 
[root@wangtian day02]# cat 15.py 
#!/usr/bin/python
fd = open('/tmp/tmp.txt')
for line in fd:
    print line,
[root@wangtian day02]# python 15.py 
1
2
3

  

小结:

print line后面加个逗号,可以抑制print默认的换行。
for line in fd.readlines(): 这种方法会全部加在到内存中,不建议使用
for line in fd: 这种方法类似于fd.next(),没循环一次加在一行,推荐使用。

总结

打开文件的时候要使用w方法会覆盖原来的文件,谨慎使用
read(),readline()readlins()的区别是字符串和列表
使用方法的时候选择最小消耗资源的方式

while循环

[root@wangtian day02]# cat 16.py 
#!/usr/bin/python

fd = open('/tmp/tmp.txt')
while True: 
    line = fd.readline()
    if not line:
        break 
    print line,
fd.close
[root@wangtian day02]# python 16.py 
1
2
3

  

with+while循环

[root@wangtian day02]# cat 17.py 
#!/usr/bin/python

with open('/tmp/tmp.txt') as fd:
    while True: 
        line = fd.readline()
        if not line:
            break 
        print line,
[root@wangtian day02]# python 17.py
1
2
3

  

总结

for循环有一定的次数
while循环需要给出条件,条件语句后面要加:
for和while遍历完文件之后需要加fd.close关闭文件,养成好习惯,如果不加python执行完系统也会进行回收
with+while进行循环就不用加close的方法


字符串方法


 
a.   
            a.capitalize a.decode     a.expandtabs a.index      a.isdigit    a.istitle    a.ljust      a.partition  a.rindex     a.rsplit     a.splitlines a.swapcase   a.upper      
            a.center     a.encode     a.find       a.isalnum    a.islower    a.isupper    a.lower      a.replace    a.rjust      a.rstrip     a.startswith a.title      a.zfill      
            a.count      a.endswith   a.format     a.isalpha    a.isspace    a.join       a.lstrip     a.rfind      a.rpartition a.split      a.strip      a.translate    

  

   
 
 

统计内存python脚本

 
[root@wangtian day02]# cat 18.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' 
[root@wangtian day02]# python 18.py 
792.20M
 
 

小结

str.startswith:以什么开头的方法,返回bool值,是返回True,否返回false
str.split:切割文本的方法,默认以空格和TAB键进行分割,返回的是字符串列表。
a.lower:大替换小写的方法
a.upper:小替换大写的方法
%s和%f都是对字符串进行格式化
%.2f表示保留两位小数
int():表示对字符串转换成整数。
1024.0:表示浮点数
+‘M’:表示进行字符串的拼接

 
 
 
选择了奋斗,以后可以随时还有选择安逸的权力。 但选择了安逸,可能以后就不那么轻易还能有选择奋斗的权力。
原文地址:https://www.cnblogs.com/wtli/p/7696643.html