This article mainly introduces several tips on collecting Python, such as obtaining the name of the current machine, obtaining the current working path, and obtaining the temporary directory of the system. For more information, see
Obtain the name of the current machine:
The code is as follows:
Def hostname ():
Sys = OS. name
If sys = 'nt ':
Hostname = OS. getenv ('computername ')
Return hostname
Elif sys = 'posix ':
Host = OS. popen ('echo $ hostname ')
Try:
Hostname = host. read ()
Return hostname
Finally:
Host. close ()
Else:
Return 'unkwon hostname'
Obtain the current job path:
The code is as follows:
Import OS
OS. getcwd ()
# Or
# OS. curdir just return. for current working directory.
# Need abspath () to get full path.
OS. path. abspath (OS. curdir)
Obtain the temporary directory of the system:
The code is as follows:
OS. getenv ('temp ')
Conversion of string and int, long, float:
Python variables seem to have no type, but they actually have a type.
Use atoi and atof in the locale module to convert a string to int or float, or directly use int (), float (), str () to convert it. In earlier versions, atoi and atof are in the string Module.
The code is as follows:
S = "1233423423423423"
Import locale
Locale. atoi (s)
#1233423423423423
Locale. atof (s)
#1233423423423423.0
Int (s)
#1233423423423423
Float (s)
#1233423423423423.0
Str (0, 123434)
"123434"
Conversion of bytes and unicodestr:
The code is as follows:
# Bytes object
B = B "example"
# Str object
S = "example"
# Str to bytes
Bytes (s, encoding = "utf8 ")
# Bytes to str
Str (B, encoding = "UTF-8 ")
# An alternative method
# Str to bytes
Str. encode (s)
# Bytes to str
Bytes. decode (B)
The following code must be used to write platform-independent code:
The code is as follows:
>>> Import OS
>>> OS. pathsep
';'
>>> OS. sep
'\\'
>>> OS. linesep
'\ R \ n'