文件操作及相关异常处理
标签(空格分隔): 文件,打开
- 打开文件
Python使用内置的open()
函数打开一个文件,并且返回一个文件对象,也叫句柄(handle)。python f = open("test.txt") # 在本文件夹下面的一个文件 f = open("C:/Python33/README.txt") # 全路径
- 关闭文件
- 默认方法:
f = open("app.log", 'r') do_something() f.close()
但是这个办法不安全,因为在进行其他操作时,可能会出现异常,程序退出,那么关闭文件的语句就不会被执行。- 为了避免异常,可以使用<
try-finally
>语句来处理
try: f = open('app.log', 'r') do_something() finally: f.close()
- 官网给出的最佳用法
with open('app.log', 'r') as f: do_something()
- 文件操作
- 写入文件
- 单独字符串写入(
write()
方法)
lines = ['line1', 'line2'] with open('filename.txt', 'w') as f: s = '' for data in lines: s += data s += '\n' f.write(s)
引入join()函数写入python lines = ['line1', 'line2'] with open('filename.txt', 'w') as f: f.write('\n'.join(lines))
writelines()
方法写入
lines = ['line1', 'line2'] with open('filename.txt', 'w') as f: f.writelines("%s\n" % l for l in lines)
- 单独字符串写入(
- 文件读取
read()方法
result = f.read()
这里返回的是文件内容,是str类型的结果,这个方法还带一个数值类型的参数,指定读取多少内容,如果省略了或者是负数,那么就返回文件的全部内容。readline()方法
result = f.readline()
返回的也是字符串,不过是一行内容,继续调用,就会返回下一行内容readlines()方法
result = f.readlines()
这里返回的是一个列表,但是当数据较大时,这样的用法会很占用内存,不推荐在数据量大时使用- 直接循环文件对象
for line in f: print line do_something()
这样的用法节省内存,快速,并且代码还简单
- 大文件的读取
with open("log.txt") as f: for line in f: do_something_with(line)
- 写入文件
- 处理数据(csv文件格式)
步骤包括:利用csv.reader()
函数创建csv模块的读取器(** 迭代器[每次迭代完元素就消失] **) --> 循环调用next()函数读取每一行的数据
import csv from datetime import datetime from matplotlib import pyplot as plt filename = 'guangzhou-2017.csv' # 打开文件 with open(filename) as f: # 创建cvs文件读取器 reader = csv.reader(f) # 读取第一行,这行是表头数据。 header_row = next(reader) print(header_row) # 定义读取起始日期 start_date = datetime(2017, 6, 30) # 定义结束日期 end_date = datetime(2017, 8, 1) # 定义3个list列表作为展示的数据 dates, highs, lows = [], [], [] for row in reader: # 将第一列的值格式化为日期 d = datetime.strptime(row[0], '%Y-%m-%d') # 只展示2017年7月的数据 if start_date < d < end_date: dates.append(d) highs.append(int(row[1])) lows.append(int(row[2])) # 配置图形 fig = plt.figure(dpi=128, figsize=(12, 9)) # 绘制最高气温的折线 plt.plot(dates, highs, c='red', label='Highest temperature', alpha=0.5, linewidth = 2.0, linestyle = '-', marker='v') # 再绘制一条折线 plt.plot(dates, lows, c='blue', label='Lowest temperature', alpha=0.5, linewidth = 3.0, linestyle = '-.', marker='o') # 为两个数据的绘图区域填充颜色 plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) # 设置标题 plt.title("the temperature of Guangzhou 2017-7") # 为两条坐标轴设置名称 plt.xlabel("date") # 该方法绘制斜着的日期标签 fig.autofmt_xdate() plt.ylabel("Temperature(℃)") # 显示图例 plt.legend() ax = plt.gca() # 设置右边坐标轴线的颜色(设置为none表示不显示) ax.spines['right'].set_color('none') # 设置顶部坐标轴线的颜色(设置为none表示不显示) ax.spines['top'].set_color('none') plt.show()