广州石井做网站,商业空间设计主要有以下几点,网站开发的安全策略,怎么制作免费的企业网站读取文件
使用open()打开文件#xff0c;文件不存在会抛出IOError错误。 try:
f open(/path/to/file, r)
print(f.read())
finally:
if f:
f.close()
文件读取完成一定要close()#xff0c;为了保证在报错的时候也能close()#xff0c;这里用了finally语句#xff0c;更简…读取文件
使用open()打开文件文件不存在会抛出IOError错误。 try:
f open(/path/to/file, r)
print(f.read())
finally:
if f:
f.close()
文件读取完成一定要close()为了保证在报错的时候也能close()这里用了finally语句更简洁的写法是用with语句会自动关闭。 with open(/path/to/file, r) as f:
print(f.read())
第二个参数r读取文本文件如果要读取二进制文件使用rb。
读取大文件
很小的文件直接使用read()读取大文件超过1G需要考虑使用分片或者单行读取或者迭代之类的。
readlines读取
with open(filename, rb) as f:
for line in f.readlines():
print(line.strip().decode())
read(size)分片读取
使用read(chunk_size)指定大小去分片读取文件。 with open(filePath, rb) as f:
while True:
chunk_data f.read(chunk_size)
if not chunk_data:
break
print(chunk_data.strip().decode())
迭代行 with open(filename, rb) as f:
for line in f:
print(line.strip().decode())
strip()去掉末尾换行
decode()将二进制转换成字符串
读取非utf-8编码
指定编码比如gbk。 f open(/Users/michael/gbk.txt, r, encodinggbk)
f open(/Users/michael/gbk.txt, r, encodinggbk, errorsignore) # 忽略错误
写入文件
传入标识符w或者wb表示写文本文件或写二进制文件 with open(/Users/michael/test.txt, w) as f:
f.write(Hello, world!)
以w模式写入文件时如果文件不存在会新建如果文件已存在会直接覆盖内容。
追加写入
传入a以append模式写入。写入中文时指定编码utf8防止乱码。 with open(/Users/michael/test.txt, a, encodingutf8) as f:
f.write(\n追加写入Hello, world!)
Python笔记文件IO操作
更多精彩敬请关注本博微信公众号hsu1943