Used to process file content in the system
Under what circumstances do I need to process files?§ Read the configuration file § read the data information § analyze and process the log file § Save the data to the file
Open a file
Method 1:Open ('filename', ['Mode'])
Method 2:File ('filename', ['Mode'])
Mode:A: append W: Write and replace old one R: read, default mode B: binary files +: read/write mode (R +: Read and append. W +: read and write. A +: readable and appendable)
For example:
>>> open(‘/root/file.txt‘)<open file ‘/root/file.txt‘, mode ‘r‘ at 0x7fa536269540>>>> open(‘/root/file.txt‘,‘w‘)<open file ‘/root/file.txt‘, mode ‘w‘ at 0x7fa5362694b0>>>> file(‘/root/file.txt‘,‘a‘)<open file ‘/root/file.txt‘, mode ‘a‘ at 0x7fa536269540>
Read a file (Readline, readlines ):
Readline reads a file in one row until it is read;
Readlines reads the end of the text from the current line.
>>> a=open(‘/root/file.txt‘)
>>> a.readline()
‘1:root:x:0:0:root:/root:/bin/bash\n‘
>>> a.readline()
‘2:bin:x:1:1:bin:/bin:/sbin/nologin\n‘
>>> a.readlines()
[‘3:daemon:x:2:2:daemon:/sbin:/sbin/nologin\n‘,‘4:adm:x:3:4:adm:/var/adm:/sbin/nologin\n‘,‘5:lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n‘]
>>> a.readline()
‘‘
Write () Write a row>>> A = open ('/root/file.txt', 'A') >>>. write ('6: mysql: X: 4: 7: LP:/var/spool/lpd:/sbin/nologin \ n')>. close () truncate (n) file content is retained for only 2 Characters >>> A = open ('/root/file.txt', 'A') >>>. truncate (2) >>>. close ()
Seek (n) the cursor returns to the nth character at the beginning of the file. For example, seek (0) returns to the beginning.>>> A. Seek (0) >>> A. Readline () 'root: X: 0: 0: Root:/root:/bin/bash \ N'
Exercise: print a complete file
#!/usr/bin/pythonfile=open(‘/root/file.txt‘,‘r‘)whileTrue: line = file.readline() if len(line)==0:break print line,
Exercise: print files and use split (':') to implement functions similar to awk:
#!/usr/bin/pythonfile=open(‘/root/file.txt‘,‘r‘)whileTrue: line = file.readline() if len(line)==0:break newline = line.split(‘:‘) print newline[0],‘--‘,newline[1][[email protected] python_scripts]# python 8file.py root -- xbin -- xdaemon -- xadm -- xlp -- x
Exercises:
Employee information is stored in the file emp.info. Read the file, list the employee IDs in the file, and output the employee details based on the employee ID.
[[email protected] python_scripts]# cat emp.info01 lk 18610314061 it02 tom 13539393939 net03 jack 15093949348 mark04 james 13892387464 sale
#!/usr/bin/pythonfile=open(‘/root/python_scripts/emp.info‘,‘r‘)emp_ids=[]whileTrue: line=file.readline() if len(line)==0:break line=line.split() emp_ids.append(line[0])print emp_idswhileTrue: id = raw_input(‘input [id] to show info:‘) file.seek(0) whileTrue: line=file.readline() if len(line)==0: print ‘We dont have id ‘,id break if id == line.split()[0]: print line file.seek(0) id = raw_input(‘input [id] to show info:‘)
5. File Processing