Python is a commonly used computer language in a wide range of applications, today, we will introduce how to operate related files in common Python Module I. The following is an introduction to this article. I hope you will gain some benefits.
Open a file
- f = open("filename", "r")
R read-only w write rw read/write rb Read Binary wb write binary w + write append read/write File
F. write ("a") f. write (str) write a string f. writeline ()
F. readlines () is similar to the lower read
- F. read () all read out f. read (size) indicates reading size characters from the file
- F. readline () reads a row and ends with the end of the file. f. readlines () is returned ()
Read all, return a list. list each element represents a row, contains "\ n "\
- F. tell () returns the current file read location
- F. seek (off, where) locates the file read/write position. off indicates the offset,
A positive number moves toward the end of the file. A negative number indicates moving toward the beginning.
- Where 0 indicates the start time, 1 indicates the current position, and 2 indicates the end time.
- F. flush () refresh the cache
Close files in Python Module I
- f.close()
- regular expression_r_r_r_r_r_r_r_r
Regular Expression import re simple regexp
- p = re.compile("abc") if p.match("abc") : print "match"
In the above example, the first character is a pattern. If it matches a string, a match object is returned. Except for some special characters, metacharacter metacter. Most of the characters match itself.
These special characters are
- 。^ $ * + ? { [ ] \ | ( )
Character Set combination (expressed in)
Listing characters. For example, [abc] indicates matching a, B, or c. Most metacharacters only indicate matching with themselves in. Example: a = ". ^ $ * +? {\\| () "Most metachar matches itself in [], but" ^ [] \ "is different
- p = re.compile("["+a+"]")
- for i in a:
- if p.match(i):
- print "[%s] is match" %i
- else:
- print "[%s] is not match" %i
[] Contains [], indicating "[" or "]" matching. it is represented by \ [and. ^ it appears at the beginning of [], indicating reverse. [^ abc] indicates all characters except a, B, and c. ^ It does not appear at the beginning, that is, body matching. -The range. [a-zA-Z] matches any English letter. [0-9] matches any number. \ Wonderful use in.
- \d [0-9]
- \D [^0-9]
- \s [ \t\n\r\f\v]
- \S [^ \t\n\r\f\v]
- \w [a-zA-Z0-9_]
- \W [^a-zA-Z0-9_]
The above article introduces file operations in Python Module I.