Some basic knowledge of Python needed to remember.
Collected from the Internet when I deal with my graduate design.
1. Encode & Decode
How to encode? (转编码)
Convert unicode to general Python String.
unicodestring = u"Hello world"
utf8string = unicodestring.encode("utf-8")
asciistring = unicodestring.encode("ascii")
isostring = unicodestring.encode("ISO-8859-1")
utf16string = unicodestring.encode("utf-16”)
How to decode? (解码)
Convert general Python String to unicode.
plainstring1 = unicode(utf8string, "utf-8")
plainstring2 = unicode(asciistring, "ascii")
plainstring3 = unicode(isostring, "ISO-8859-1")
plainstring4 = unicode(utf16string, "utf-16")
# whether they are equal
assert plainstring1==plainstring2==plainstring3==plainstring4
2. Type Conversion
unicode -> string: str(unicode)
float -> int: int(float)
3. Time Related
Get timely time?
import time
# 1494407653.527396
time.time()
# time.struct_time(tm_year=2017, tm_mon=5, tm_mday=10, tm_hour=17, tm_min=14, tm_sec=32, tm_wday=2, tm_yday=130, tm_isdst=0)
time.localtime()
# format = '%Y-%m-%d %H:%M:%S'; time = none/time.localtime()
# >>> time.strftime('%Y-%m-%d %H-%M-%S', time.localtime())
# '2017-05-10 17-20-37'
time.strftime(format, time)
# a better way to show
# 'Wed May 10 17:22:55 2017'
time.ctime()
time.sleep(10)
4. File & Folder
Whether file or folder exists?
import os
os.path.isfile('test.txt') # return true or false
os.path.exists(directory) # return true or false
How to new or delete a file or folder?
File
# (new)write to a file
# w+: write; r+: read
fo = open(filePath, "w+")
fo.write(ds.content)
# read a file
# readlines() can be used to iterately read all data in the file
fo = open(filePath, 'r+')
with open(i) as f:
for j in f.readlines():
line = j.rstrip(',\n')
# Rename file1.txt to file2.txt
os.rename( "file1.txt", "file2.txt" )
# Remove a file
os.remove("file.txt")
Folder
# new a folder
os.mkdir(dirName)
# change a folder directory
os.chdir("../barrageData")
# remove a folder
os.remove(dirName)