Python Notes: Basic Knowledge

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?

In detail in Chinese

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)

5. String

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 个人笔记,方便自己查阅使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik阅读 67,777评论 0 5
  • “我对于你是如晚霞般美丽的记忆,回想我们珍贵的青涩的日子,将它珍藏为心中无憾的画面。你对于我是将曾有的孤单驱散的阳...
    芈修阅读 423评论 2 2
  • 某夜梦见了贾胖子,早晨睁开眼努力回想,仿佛看见那只肉嘟嘟的手拍着我的肩膀皮笑肉不笑地说:“年轻人,要珍惜机会啊!”...
    老瘾阅读 793评论 0 0
  • 看《窗边的小豆豆》还是很有心得的,有可能是对其中的一段话一个行为,还是瞬间记载下来比较好,否则就找不到当时的感触了...
    海豚的微笑阅读 234评论 0 0
  • 写作。我很想写点东西 我想起上学时候的我 很讨厌作文 每次考试却又很快能写完。不是想象中那样讨厌却擅长。只不过是乱...
    小酒owo阅读 181评论 0 1