startswith()
And endswith()
methods provide a very convenient way to do the beginning and end of the string check.
1. View all file names under the specified directory
>>>ImportOS>>> filenames = Os.listdir ('I:\PythonTest')>>>filenames['111.csv','111.xlsx','111.xml','123.txt','123.xlsx','123123.xml','123123.xml.bak','1234.txt','222.xml','Book.xml','Book.xml.bak','Excelwrite.csv','excelwrite.xlsx','koala.jpg','Movie.xml','Movie.xml.bak','Movies.xml','Receive.txt','User.xml','User.xml.bak','New Folder']
2. list. txt file names
for inch Filenames: if i.endswith ('.txt') :print(i )123 . txt1234. Txtreceive.txt
Another way to do this:
>>> I forIinchFilenamesifI.endswith ('. txt') Syntaxerror:invalid Syntax>>> [i forIinchFilenamesifI.endswith ('. txt')] #结果返回一个list [] ['123.txt','1234.txt','Receive.txt']>>> a = [i forIinchFilenamesifI.endswith ('. txt')]>>>Print(a) ['123.txt','1234.txt','Receive.txt']
3.. txt and. xml files are listed at the same time
If you want to check for multiple matches, just put all the matches into a tuple (' A ', ' B ', ' C ') , and then pass startswith()
or endswith()
method
>>> forIinchFilenames:ifI.endswith (('. txt','. XML')): Print(i)111. XML123. txt123123. XML1234. txt222. Xmlbook.xmlmovie.xmlmovies.xmlreceive.txtuser.xml>>> [i forIinchFilenamesifI.endswith (('. txt','. XML'))]['111.xml','123.txt','123123.xml','1234.txt','222.xml','Book.xml','Movie.xml','Movies.xml','Receive.txt','User.xml']
4. list file names starting with book and 1
>>> [i forIinchFilenamesifI.startswith ((' Book','1'))]['111.csv','111.xlsx','111.xml','123.txt','123.xlsx','123123.xml','123123.xml.bak','1234.txt','Book.xml','Book.xml.bak']
5. See if there is an XML file
Check that the specified file type exists in a folder:
If any (Name.endswith (". C ', '. h ')) for name in Listdir (dirname)):
>>> any (Name.endswith ('. xml' as in filenames) True
Reference: http://python3-cookbook.readthedocs.org/zh_CN/latest/c02/p02_match_text_at_start_end.html
python-string start or End match