Python OS. Path module/Python OS. listdir/string processing/Python time datetime. datetime

Source: Internet
Author: User
Tags month name printable characters
1.1 Python OS. Path Module

OS. Path. abspath (PATH) # returns the absolute path.

OS. Path. basename (PATH) # returns the file name OS. Path. commonprefix (list) # returns the longest path of all paths in List (multiple paths. OS. path. dirname (PATH) # returns the file path OS. path. exists (PATH) # True is returned if the path exists, and falseos is returned if the path is damaged. path. lexists # If the path exists, true is returned. If the path is damaged, trueos is returned. path. expanduser (PATH) # Put "~ "And "~ Convert user to user directory OS. path. expandvars (PATH) # Replace the "$ name" and "$ {name}" OS in the path based on the value of the environment variable. path. getatime (PATH) # returns the last time the path was entered. OS. Path. getmtime (PATH) # returns the last modification time under this path. OS. path. getctime (PATH) # returns the size of the path OS. path. getsize (PATH) # returns the file size. If the file does not exist, the system returns the error OS. path. isabs (PATH) # determine whether it is an absolute path OS. path. isfile (PATH) # determine whether the path is a file OS. path. isdir (PATH) # determine whether the path is a directory OS. path. islink (PATH) # determine whether the path is linked to the OS. path. ismount (PATH) # determine whether the path is a mount point () OS. path. join (path1 [, path2 [,...]) # combine the Directory and file name into a path OS. path. normcase (PATH) # convert the case and slash OS of the path. path. normpath (PATH) # standard path string form OS. path. realpath (PATH) # returns the real path OS of path. path. relpath (path [, start]) # Calculate the relative path OS from start. path. samefile (path1, path2) # determine whether the directory or file is the same as OS. path. sameopenfile (FP1, fp2) # determine whether FP1 and fp2 point to the same file OS. path. samestat (STAT1, stat2) # determine whether stat tuple STAT1 and stat2 point to the same file OS. path. split (PATH) # divide the path into dirname and basename, and return an OS. path. splitdrive (PATH) # It is generally used in windows and returns the OS, which consists of the drive name and path. path. splitext (PATH) # split the path, and the OS with the path name and file extension is returned. path. splitunc (PATH) # splits the path into a load point and a file OS. path. walk (path, visit, ARG) # traverse the path and call the visit function in each directory. The visit function must have three parameters (ARG, dirname, names ), dirname indicates the Directory Name of the current directory, names indicates all file names in the current directory, and ARGs indicates the third parameter OS of the walk. path. supports_unicode_filenames # Sets whether Unicode path names are supported

1.2 Python OS. listdir

In Python OS. in listdir, we can list the specific operation solutions of all related files and directories in Dir, and how to use the OS in Python. path. the isfile () function is used to determine whether the relevant path is a file. The following is a detailed description of the article.

Python determines whether a file is used in the python OS. listdir function to determine whether a path is a file. The function prototype is as follows.

 
 
  1. os.path.isfile(path) 

The parameter meanings are as follows. Path: The Path to be determined. The following example checks whether E: \ book \ Temp is a file.

 
 
  1. >>> import os  
  2. >>> os.path.isfile('E:\\book\\temp')   

Determine whether it is a file

 
 
  1. False  

E: \ book \ Temp is not used to list all files in the directory.

Keywords:

 
 
  1. dirimport string, os, sys  
  2. dir = '/var' 
  3. print '----------- no sub dir'  
  4. files = os.listdir(dir)  
  5. for f in files:  
  6. print dir + os.sep + f  
  7. print '----------- all dir'  
  8. for root, dirs, files in os.walk(dir):  
  9. for name in files:  
  10. print os.path.join(root, name)   

The preceding Python OS. listdir can list all files and directories in Dir, but does not include contents in subdirectories. OS. Walk can traverse all the following directories, including subdirectories.

1.3 string processing

Judgement-A bool value is usually returned.
Str. isalpha () Whether to include only text
Str. isdecimal () Whether to include only numbers (multilingual numbers)
Str. isdigit () Whether to include only numbers (0 ~ 9)
Str. isnumeric () Whether to contain only numeric characters
Str. isalnum () Whether it only contains text and numbers
Str. isidentifier () Is it a legal identifier?
Str. islower () Lowercase?
Str. isupper () Are all uppercase letters?
Str. istitle () Whether the first letter of each word is capitalized
Str. isprintable () Whether to include only printable characters
Str. isspace () Whether to contain only white space characters
Str. startswith (prefix [,
Start [, end])
Prefix or not
Str. endswith (suffix [,
Start [, end])
End with suffix?
Modifier-a modified string is usually returned.
Str. capitalize () Returns an uppercase string.
Str. Title () Returns an uppercase string of each word.
Str. expandtabs ([tabsize]) "\ T" to convert to Space
Str. Upper () Full conversion to uppercase
Str. Lower () Convert all to lowercase letters
Str. Ljust (width [,
Fillchar])
Align left and fill right
Str. Must ust (width [,
Fillchar])
Right alignment, left Filling
Str. Center (width [,
Fillchar])
Center, filled on both sides
Str. lstrip ([chars]) Remove left white space or custom characters
Str. rstrip ([chars]) Remove right white space or custom characters
Str. Strip ([chars]) Remove white spaces or custom characters on both sides
Str. swapcase () Case sensitivity
Str. zfill (width) Fill the left side with 0 to the specified width, which is generally used to modify numbers
Search & replace
Str. Count (sub [,
Start [, end])
Calculate the number of sub occurrences between [start, end)
Str. Find (sub [, start [, end])  
Str. Index (sub [, start [, end])  
Str. rfind (sub [, start [, end])  
Str. rindex (sub [, start [, end])  
Str. Replace (old, new [, Count])  
Splitting & Combination
Str. Join (iterable)  
Str. Partition (SEP)  
Str. rpartition (SEP)  
Str. Split ([Sep [, maxsplit])  
Str. rsplit ([Sep [, maxsplit])  
Str. splitlines ([keepends])  
Conversion
Hex (X)  
INT ([number | string [, base])  
Len (s)  
List ([iterable])  
Oct (X)  
Ord (c)  
Repr (object)  
Reversed (SEQ)  
STR ([object [, encoding [, errors])  
Upper top priority Str. isalpha ()
-Whether to include only text
Code Result
Print ("China ABC". isalpha ()) True
Print ("". isalpha ()) False
Print ("123". isalpha ()) False
Print ("". isalpha ()) False
Maximum top priority Str. isdecimal ()
-Whether to include only decimal numbers, including multilingual numbers
Code Result
Prints ("1234567890". isdecimal ()) True
Print ("\ u0660". isdecimal ()) True
Print ("ABC". isdecimal ()) False
Print ("". isdecimal ()) False

For numbers in other languages see http://www.fileformat.info/info/unicode/category/Nd/list.htm

Upper top priority Str. isdigit ()
-Whether to include only numbers (0 ~ 9)
Code Result
Print ("1234567890". isdigit ()) True
Print ("\ u0660". isdigit ()) True
Print ("ABC". isdigit ()) False
Print ("". isdigit ()) False
Maximum top priority Str. isnumeric ()
-Whether to include only numeric characters
Code Result
Print ("1234567890". isnumeric ()) True
Print ("\ u2155". isnumeric ()) True
Print ("ABC". isnumeric ()) False
Print ("". isnumeric ()) False

For numeric characters, see http://www.fileformat.info/info/unicode/category/No/list.htm

Maximum top priority Str. isalnum ()
-Whether to include only text and numbers
Code Result
Print ("abc123456 \ u2155". isalnum ()) True
Print ("". isalnum ()) False
Print ("\ t". isalnum ()) False
Print ("". isalnum ()) False
Maximum top priority Str. isidentifier ()
-Is it a legal identifier?
Code Result
Print ("if". isidentifier ()) True
Print ("China". isidentifier ()) True
Print ("123". isidentifier ()) False
Print ("". isidentifier ()) False
Comment top comment Str. islower ()
-Whether it is in lower case
Code Result
Print ("ABC". islower ()) True
Print ("ABC". islower ()) False
Print ("China". islower ()) False
Print ("". islower ()) False
Upper top priority Str. isupper ()
-Are all uppercase letters?
Code Result
Print ("Hello world". istitle ()) True
Print ("Hello world". istitle ()) False
Print ("Hello world". istitle ()) False
Print ("". istitle ()) False
Upper top priority Str. istitle ()
-Whether the first letter of each word is capitalized
Code Result
Print ("Hello world". istitle ()) True
Print ("Hello world". istitle ()) False
Print ("Hello world". istitle ()) False
Print ("". istitle ()) False
Wrote top response Str. isprintable ()
-Whether to include only printable characters
Code Result
Print ("a B". isprintable ()) True
Print ("". isprintable ()) True
Print ("ABC \ t". isprintable ()) False
Print ("ABC \ n". isprintable ()) False
Maximum top priority Str. isspace ()
-Whether to include only white space characters
Code Result
Print ("". isspace ()) True
Print ("\ t \ n". isspace ()) True
Print ("a B". isspace ()) False
Print ("". isspace ()) False
Upper top priority Str. startswith (prefix [,
Start [, end])-whether to start with prefix
Code Result
Print ("Chinese". startswith ("medium ")) True
Print ("Chinese". startswith ("China", "I "))) True
Wrote top response Str. endswith (suffix [,
Start [, end])-whether to end with suffix
Code Result
Print ("Chinese". endswith ("person ")) True
Print ("Chinese". endswith ("Chinese", "I "))) True
Upper top priority Str. capitalize ()
-Returns an uppercase string.
Code Print ("the first sentence. The second sentence.". capitalize ())
Result The first sentence. The second sentence.
Top priority Str. Title ()
-Returns an uppercase string of each letter.
Code Print ("this is a title". Title ())
Result This is a title
Using Top response Str. expandtabs ([tabsize])
-"\ T" to convert to Space
Code "\ T". expandtabs (8)
Result ''
Upper top priority Str. Upper ()
-Full conversion to uppercase
Code Print ("ABC". Upper ())
Result ABC
Comment top comment Str. Lower ()
-Convert all data to lowercase letters.
Code Print ("ABC". Upper ())
Result ABC
Upper top priority Str. Ljust (width [,
Fillchar])-align left and fill right
Code Print ("I". Ljust (4, ""))
Result

We

Upper top priority Str. Must ust (width [,
Fillchar])-Right alignment, left Filling
Code Print ("I". Allowed ust (4, "= "))
Result

=== Me

Upper top priority Str. Center (width [,
Fillchar])-center, filled on both sides
Code Print ("I Am a split line". Center (30, "= "))
Result ================ I am a split line ======================
Upper top priority Str. lstrip ([chars])
-Remove left white space or custom characters
Code 'Spacious '. lstrip ()
Result 'Spacious'
Code 'Www .example.com '. lstrip ('cmowz .')
Result 'Example. com'
Upper top priority Str. rstrip ([chars])
-Remove right white spaces or custom characters
Code 'Spacious '. rstrip ()
Result 'Spacious'
Code 'Mississippi '. rstrip ('ipz ')
Result 'Mississ'
Upper top priority Str. Strip ([chars])
-Remove blank spaces or custom characters on both sides
Code 'Spacious '. Strip ()
Result 'Spacious'
Code 'Www .example.com '. Strip ('cmowz .')
Result 'Example'
Using Top response Str. swapcase ()
-Case-insensitive Conversion
Code Print ("ABC". swapcase ())
Result ABC
Upper top response Str. zfill (width)
-Fill the left side with 0 to the specified width, which is generally used to modify numbers.
Code Print ("15". zfill (8 ))
Result 00000015
Code Print ("-15". zfill (8 ))
Result -0000015
Running Top response Str. Count (sub [,
Start [, end])-calculates the number of sub occurrences between [start, end ).
Code Print ("abababab". Count ("Abab ")
Result 2

Note: non-overlapping count, so the result is 2 instead of 3

1.4 datetime. datetime

Obtain the current time and output it using a string.

Format: % Y-% m-% d % H: % m: % s'

Datetime. datetime. Now (). strftime ('% Y-% m-% d % H: % m: % s ')

Obtains the current time, but only retains the date.

Datetime. datetime. Now (). Date ()

Convert string to datetime type

Input string format: '% Y-% m-% d'

Datetime. datetime. strptime (time, '% Y-% m-% D ')

 

Print 'start at: ', datetime. datetime. Now (). strftime (' % Y-% m-% d % H: % m: % S. % F ')
Print 'start at: ', time. strftime ('% Y-% m-% d % H: % m: % S. % F', time. localtime (time. time ()))

Appendix:

Formatted symbol Summary
% A: weekday name, abbr.
% A full name of the day of the week
Abbreviated month name, abbr.
% B full name of month name
% C standard date string complete Date and Time Representation
% D day of the month in decimal format
% H hour in the 24-hour format (24-hour clock)
% I hour in 12-hour format (12-hour clock)
% J day of the year in decimal format
Month number in % m decimal format
% M decimal representation of minutes minute number
% S decimal second number
% U indicates the week of the year. Sunday is regarded as the first day (value ranges from 0 to 53) Week number (Sunday first weekday)
% W decimal indicates the day of the week (the value ranges from 0 to 6, and Sunday is 0) weekday number
% W indicates the week of the year. Monday is regarded as the first day (from 0 to 53) Week number (Monday first weekday)
% X standard date string complete date representation (e.g. 13/01/08)
% X standard time string complete time representation (e.g. 17:02:10)
% Y decimal year without Century (value ranges from 0 to 99) year number within Century
% Y indicates the tenth year number of the century section.
% Z, % Z Time Zone name. If the time zone name cannot be obtained, an empty character is returned. Name of Time Zone
% Percent sign

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.