文件操作
读取文本文件
在读取文本文件过程中,需要设置mode=‘r’,实现只可读操作,或者不设置mode(默认就是读取操作)
finally —> 总是执行代码(不管正常异常,finally中的代码一定会被执行到)
"""
example01 - 文件操作(读取文本文件)
Author: Asus
Date: 2021/8/9
"""
import sys
print(sys.getdefaultencoding())
file = open(file='files/致橡树.txt', mode='r', encoding='utf-8')
try:
data = file.read(32)
while data:
print(data, end='')
data = file.read(32)
except:
print('读文件时发生错误')
finally:
file.close()
读取二进制文件(字节文件)
如果希望获得文件的字节数,可以先用seek方法将文件指针移动到文件末尾 然后通过tell方法获取文件指针移动的字节数,这个字节数就是文件的大小
"""
example02 - 文件操作(读取二进制文件(字节文件))
Author: Asus
Date: 2021/8/9
"""
from io import SEEK_END, SEEK_SET
file = open(file='files/guido.jpg', mode='rb')
file.seek(0, SEEK_END)
print(file.tell())
file.seek(0, SEEK_SET)
try:
data = file.read(1024)
while data:
print(data, end='')
data = file.read(1024)
finally:
file.close()
读取Python官方解释器文件
计算MD5哈希码(签名、指纹、摘要)
计算MD5哈希码,目的是检验下载的官方解释器是否被侵入
"""
example03 - 读取Python官方解释器文件,计算MD5哈希码(签名、指纹、摘要)
Author: Asus
Date: 2021/8/9
"""
from hashlib import md5, sha256
hasher = md5()
file = open('files/python-3.9.6-amd64.exe', 'rb')
try:
data = file.read(512)
while data:
hasher.update(data)
data = file.read(512)
finally:
file.close()
print(hasher.hexdigest())
写文本文件
在写文本文件过程中,需要设置mode=‘w’,实现写操作(会截断之前的内容)
如需要追加内容,则需要把参数改为mode=‘a’
"""
example04 - 文件操作(写文本文件)
Author: Asus
Date: 2021/8/9
"""
file = open('files/小雨康桥的诗.txt', mode='w', encoding='utf-8')
try:
file.write('我做燕子\n')
file.write('只需简单思想\n')
file.write('只求风中流浪\n')
file.write('我想做树\n')
file.write('不会寸断肝肠\n')
finally:
file.close()
with - 上下文语法 - 进入和离开with的时候会自动执行某些操作 下面的写法在离开with上下文的时候,会自动执行file对象的close()方法 操作模式 - a - 创建新文件或将文件指针移动到原文件末尾再写入新内容
example05 - 文件操作(写文件操作)
Author: Asus
Date: 2021/8/9
"""
with open('files/小雨康桥的诗.txt', mode='a', encoding='utf-8') as file:
file.write('我做不成燕子\n')
file.write('所以我飞不过感情的墙\n')
file.write('我做不成树\n')
file.write('因此也撑不破伤心的网\n')
文件复制
"""
example06 - 文件复制
Author: Asus
Date: 2021/8/9
"""
def file_copy(source_file, target_file):
"""文件拷贝"""
with open(source_file, 'rb') as source:
with open(target_file, 'wb') as target:
data = source.read(512)
while data:
target.write(data)
data = source.read(512)
if __name__ == '__main__':
file_copy('files/guido.jpg', '/PycharmProjects/day16/copy/Python之父.jpg')
将100以内的质数输出到文件中
"""
example07 - 将100以内的质数输出到文件中(每行一个数)。
Author: Asus
Date: 2021/8/9
"""
def is_prime(num):
if num == 2 or num == 3:
return True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def main():
with open('files/100以内的质数.txt', mode='w', encoding='utf-8') as file:
for num in range(2, 101):
if is_prime(num):
file.write(f'{num}\n')
if __name__ == '__main__':
main()
读取csv文件
delimiter —> 设置分隔符(默认是英文的逗号) quotechar —> 包裹字符串的符号(默认是英文的双引号)
"""
example09 - 读取CSV (逗号分隔值)文件---> Comma Seperated Value
Author: Asus
Date: 2021/8/9
"""
import csv
with open('files/2018年北京积分落户数据2.csv', encoding='gb18030') as file:
reader = csv.reader(file)
for row in reader:
print(reader.line_num)
print(row)
写csv文件
"""
example10 - 写csv文件
Author: Asus
Date: 2021/8/9
"""
import csv
with open('files/temperature.txt', encoding='utf-8') as file1:
with open('files/temperature发热数据.csv', mode='w', encoding='utf-8', newline='') as file2:
writer = csv.writer(file2)
writer.writerow(['ID', 'temperature', 'information'])
content = file1.readline()
while content:
no, temp = content.split()
temp = float(temp)
if temp >= 37.2:
if temp <= 38.5:
info = '发热'
else:
info = '高热'
print(no, temp, info)
writer.writerow([no, temp, info])
content = file1.readline()
temp <= 38.5:
info = '发热'
else:
info = '高热'
print(no, temp, info)
writer.writerow([no, temp, info])
content = file1.readline()
|