File operations complete these steps:
1. Open the file open hello with built-in functions, the return value is a file object
f=open("/home/centos01/hello")
2. Read the contents of the file (or write f.write ( "Content"), but it must open is writable file opened for the job)
f.read()
3. Close the file
f.close()
Other modes of file operations ( mode open function):
r is opened for reading, to locate the beginning of the file, the default mode, for example, f = open ( "/ home / centos01 / hello") is equivalent to f = open ( "/ home / centos01 / hello", 'r')
r + opened in read and write, at the beginning of the file positioning, can be written to file
w is opened for writing, the file has been emptied contents file, and can not be read
w + opened in read and write, the file header to locate and opens the file contents will be cleared when the file is
a way to write open, navigate to the end of the file, an additional operation, but do not allow to read
a + to write the way open, navigate to the end of the file, additional ways.
In using the above mode opening the file, if the increase in the b mode represents opened in binary mode, if the read file is a non-text files, can add b, EG in the original mode: 'rb', 'rb + ', 'wb +', 'ab' , 'ab +' etc.
pointer:
Create a file hello, hello content
# Coding: UTF. 8- F = Open ( " / mnt / Hello " ) Print reached, f.read () # Seek need to pass two values; # first parameter: offset; offset> 0, representing the right moving character; conversely, the character moves left; # the second argument: 0: 1 start of the file on behalf of: current position 2: end of file; f.seek (3,0) # offset three characters from the beginning of the file, the result should be read to predict "LO \ the n-" Print f.tell () # Print offset Print f.read ()
operation result:
Read the file (read, readline, readlines)
readline and readlines method:
readline method
In turn read the file, the file information returns only one row
In [1]: f=open("/mnt/passwd") In [2]: f.readline() Out[2]: 'root:x:0:0:root:/root:/bin/bash\n' In [3]: f.readline() Out[3]: 'bin:x:1:1:bin:/bin:/sbin/nologin\n'
readlines method
Way to return a list of file information, reservations line breaks
In [1]: f=open("/mnt/passwd") In [2]: f.readlines() Out[2]: ['root:x:0:0:root:/root:/bin/bash\n', 'bin:x:1:1:bin:/bin:/sbin/nologin\n', 'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n', 'adm:x:3:4:adm:/var/adm:/sbin/nologin\n', 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n', 'sync:x:5:0:sync:/sbin:/bin/sync\n', 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n', 'halt:x:7:0:halt:/sbin:/sbin/halt\n', 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n', 'operator:x:11:0:operator:/root:/sbin/nologin\n', 'games:x:12:100:games:/usr/games:/sbin/nologin\n', 'ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\n', 'nobody:x:99:99:Nobody:/:/sbin/nologin\n', 'systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\n', 'dbus:x:81:81:System message bus:/:/sbin/nologin\n', 'polkitd:x:999:998:User for polkitd:/:/sbin/nologin\n', 'sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin\n', 'postfix:x:89:89::/var/spool/postfix:/sbin/nologin\n', 'centos01:x:1000:1000:centos01:/home/centos01:/bin/bash\n', 'tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin\n']
readlines practical application:
[@ centos01 the root Python] # CAT the test.py # Coding: UTF. 8- F = Open ( " / etc / the passwd " ) Print [i.strip () for I in f.readlines ()] [:. 5] # which is a list of formula, Strip () removal space, [: 5] from the former list 5 rows f.close () [the root @ centos01 Python] # Python the test.py [ ' the root: X: 0: 0: the root: / the root: / bin / the bash ' , ' bin: X:. 1:. 1: bin: / bin: / sbin / nologin ' , ' daemon: X: 2: 2: daemon: / sbin: / sbin / nologin ' , ' ADM: X:. 3:. 4: ADM: / var / ADM: / sbin / nologin ', 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin']
Write files (write, writelines)
write
writelines
You can write multiple lines of text
[Python the root @ mnt] # CAT # hello hello view file content hello the In [ . 1]: F = Open ( " / mnt / hello " , ' A + ' ) # open the file additional embodiment the In [ 2]: f.write ( " 123 \ n- " ) # additional wrap 123 and the In [ . 3]: f.writelines ([ " Python \ n- " , " Java \ n- " ]) # append a number of lines, since writelines brackets with only one parameter , many lines can be introduced in a list the in [ . 4 ]: f.close () [the root @ Python mnt] #cat hello # view the file again, the content has changed the Hello 123 Python the Java
File object f is the iteration of it?
In [14]: f = open("/mnt/hello",'a+') In [15]: for i in f: ....: print i ....: hello python java
Visible is iterative, so we write the script can use this feature, it can be used directly to loop through all the rows in the file after file open
Built-in file attributes
print f.closed # bool return value to determine whether the file object has been closed
Open print f.mode # view files is r, w, w + ...
print f.name # view the file name (absolute path)
Forget the case after use to prevent open statement with complete file close () is: with statement
An In [24-]: with Open ( " / mnt / the Hello " ) AS f1: ....: Print f1.read () ....: the Hello Python the Java an In [ 25]: Print f1.closed # we do not use f1.closed (), and now use the built-in document property to test whether it is turned off, the result is True, it has closed the True
Exercise 1:
Display file all lines, but ignored to start with #
[root @ centos1 mnt] # cat / mnt / hello
#hello
hello
python
java
[@ centos01 the root Python] # CAT the test.py # Coding: UTF-. 8 with Open ( " / mnt / Hello " ) AS F: for Line in F: # using the iterative nature of the file object can be directly for loop iterates IF Line. ! Strip () [0] = " # " : # indicates if the first character is not a "#" ,. strip () indicates a removal string of spaces; [0] indicates the first element takes a string of Print Line, # print line, the comma indicates no change in the output line [the root @ centos01 Python] # Python the test.py Hello Python Java
Exercise 2:
The "root" string replacement / etc / passwd file as "redhat", will be replaced after Save / tmp / passwd file
[root@centos01 python]# cat test.py # coding:utf-8 with open("/etc/passwd") as f: for line in f: bline=line.replace("root","redhat") with open("/tmp/passwd","a+") as m: m.write(bline) [root@centos01 python]# python test.py [root@centos01 python]# cat /tmp/passwd redhat:x:0:0:redhat:/redhat:/bin/bash ...
Exercise 3:
Program-by-page text file, the user enters a file name, the default number of rows displayed in every 10 lines, giving the user an option, "whether to continue (y / n)"
[root@centos01 python]# cat test.py # coding:utf-8 file_name=raw_input("文件名(绝对路径):") with open(file_name) as f: li=[i.strip() for i in f.readlines()] file_length=len(li) j=0 for i in range(file_length): print li[i] j+=1 if j==10: choice=raw_input("是否继续(y/n):") if choice == " N " : # use of such a determination may be out of the loop when the user selects n, y or selected from display 10 continues to direct the transport line BREAK the else : J = 0 Continue [@ centos01 the root Python] # Python the test.py filename (absolute path): / etc / the passwd the root: X: 0: 0: the root: / the root: / bin / the bash bin: X: . 1:. 1: bin: / bin: / sbin / nologin daemon: X: 2: 2 : daemon: / sbin: / sbin / nologin ADM: X: . 3:. 4: ADM: / var / ADM: / sbin / nologin LP: X: . 4:. 7: LP: / var / spool / LPD: / sbin / nologin Sync: X: . 5: 0: Sync: / sbin: / bin / Sync the shutdown: X:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail:/sbin/nologin operator:x:11:0:operator:/root:/sbin/nologin 是否继续(y/n):n [root@centos01 python]#
Exercise 4:
All pictures will file folder name plus '_fc', and calculate the time spent and the number of pictures you are dealing with
[@ centos01 the root Python] # LS / mnt / Pictures / A.png B.png [@ centos01 the root Python] # CAT the test.py # Coding: UTF. 8- Import os # call function os Import time # call time function START_TIME = the time.time () path = ' / mnt / pictures ' # picture directory is defined as a variable, to facilitate call back Li = [I for I in the os.listdir (path) IF i.endswith ( " .png " )] # remove all the end .png / mnt / Pictures list of files li length = len (li) # Calculates the number of elements in the list for I in Range (length): oldfile to = Li [I] newfile = [I] + Li ' _fc ' # using a list of supported features behind each splice elements plus _fc os.rename (os.path.join (path, oldfile), os.path.join (path, newfile)) # os.rename ( "Old", "new new") represent modify the file name, os.path.join ( "dir1" , "dir2") expressed in / connector element to become a path END_TIME = the time.time () Print " handled% s images, when using% s " % (len (Li), end_time- START_TIME) [the root @ Python centos01] # Python test.py handled a total of two pictures with a time of 05-7.70092010498e [root @ centos01 Python] # ls /mnt/Pictures/ a.png_fc b.png_fc