Python 高级5

打印内容输出到文件

1
2
with open("a.txt", "wt") as f:
print("zhangsan", file=f)

字符串拼接打印

- 拼接内容,并以 ! 结尾

1
2
print("1111", "1111", "1111", sep="-", end="!")
# 1111-1111-1111!

使用 join 进行拼接, str.join() 的问题在于它仅仅适用于字符串

1
2
3
4
5
6
7
a = ["1111", "1111", "1111"]

print(','.join(a))
# 1111,1111,1111

print(*a, sep=",")
# 1111,1111,1111

with open 读取文件的模式

t 是以文本的方式读取或写入

1
2
with open("a.txt", "rt") as f:
print(f.read())

b 是以字节的方式读取或写入

1
2
with open("a.txt", "rb") as f:
print(f.read())

x 文件不存在才能写入,x 用于代替 w

1
2
3
with open("a.txt", "xt") as f:
f.write("zhangsan")
# 如果文件存在则提示 File exists: 'a.txt'

读写压缩文件

读取压缩文件内容

1
2
3
4
5
6
7
8
import gzip, bz2

with gzip.open('somefile.gz', 'rt') as f:
text = f.read()


with bz2.open('somefile.bz2', 'rt') as f:
text = f.read()

写入压缩数据

1
2
3
4
5
6
import gzip, bz2
with gzip.open('somefile.gz', 'wt') as f:
f.write(text)

with bz2.open('somefile.bz2', 'wt') as f:
f.write(text)