Skip to content

Python 笔记 #12

@xv-jiaqi

Description

@xv-jiaqi

Python

IO

try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f:
        f.close()

Python 引入了 with 语句来自动帮我们调用 close() 方法:

with open('/path/to/file', 'r') as f:
    print(f.read())

调用 read() 会一次性读取文件的全部内容,read(size) 方法,每次最多读取size个字节的内容。
调用 readline() 可以每次读取一行内容,调用 readlines() 一次读取所有内容并按行返回 list

bytes/str

image

# 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)

常见问题

数组去空

list(filter(lambda x: bool(x), [11, 22, '', None]))

# 或
[x for x in [11, 22, '', None] if x]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions