Python file operations
Open
R: Open in read mode
W: Open in write mode
A: in Append mode
r+: Read/write mode
w+: Read/write mode (see W)
A +: Read-write mode (see a)
RB: Open in binary read mode
WB: Opens in binary write mode (see W)
AB: Open in binary append mode (see a)
rb+: Open in binary read/write mode (see r+)
wb+: Open in binary read/write mode (see w+)
ab+: Open in binary read/write mode (see A +)
With open
Traversing a file with a for loop
Open File
[[email protected] ~]# vim forread.py#!/usr/bin/pythonfd=open ('/tmp/tmp.txt ') for line in FD: #或者使用for line in Fd.readli NES (): ReadLines () creates a list of rows, if the file is 1G, takes up memory large print line, #使用, [[email protected] ~]# python forread.py Daviddavid1david2dav Id3
Traversing a file using a while loop
Open File
[[Email protected] ~]# vim whileread.py #!/usr/bin/pythonfd = open ('/tmp/ Tmp.txt ') while true: line = fd.readline () if not line: break print Line,fd.close () [[email protected] ~]# python whileread.py daviddavid1david2david3# Use With open ()  AS FD without Fd.close (), with open The following code requires a keyword, which belongs to the looping content [[email protected] ~] # vim whileread.py #!/usr/bin/pythonwith open ('/tmp/tmp.txt ') as fd: while true: line = fd.readline () if not line: break print line,[[ Email protected] ~]#&nbSp;python whileread.py daviddavid1david2david3
Print mem Total and mem free, use StartsWith (a) to determine the beginning of a string with a letter A, return true, otherwise return False,split () to split the string
[[email protected] ~]# cat /proc/meminfo memtotal: 502092 kBMemFree: 10656 kbbuffers: 131744 kbcached: 236908 kBSwapCached: 64 kB[[email protected] ~]# vim memory.py#!/usr/bin/pythonwith 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,free[[email protected] ~]# python memory.py502092 9156
This article comes from "Plum blossom fragrance from bitter cold!" "Blog, be sure to keep this provenance http://daixuan.blog.51cto.com/5426657/1774082
Python Learning notes 4-python file operations