一、打开和关闭文件
1.open函数
可以使用Python提供的file 象做大部分的文件操作。open函数返回的就是一个file对象。其使用方式如下:
file = open(‘文件路径’, ‘文件操作方式’, encoding=‘utf-8’)
2.close函数
File 对象的 close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。当一个文件对象的引用被重新指定给另一个文件时,Python 会关闭之前的文件。用法:file.close()
二、读写文件
1.writelines函数
文本文件可以按列表写入,例如:
file = open('FileWrite.txt','w', encoding='utf-8')
file.writelines(['锄禾日当午\n','汗滴禾下土\n','谁知盘中餐\n','粒粒皆辛苦'])
file.close()
生成的文本如下图所示:
2.write函数
写文件时也可以直接写一大段文本,例如:
file = open('FileWrite2.txt','w', encoding='utf-8')
file.write('春眠不觉晓\n处处闻啼鸟\n夜来风雨声\n花落知多少')
file.close()
生成的文本文档如下所示;
3.readlines函数
文本文件可以按行读取,读取所有行,并以列表的形式返回结果,例如:
file = open('FileWrite.txt', encoding='utf-8')
text = file.readlines()
for r in text:
print(r)
file.close()
运行输出如下:
4read函数
文本文件也可以直接读取里面的所有内容,例如:
file = open('FileWrite2.txt', 'r',encoding='utf-8')
text = file.read()
print('\n')
print(text)
file.close()
结果输出如下:
代码如下(示例):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import ssl
ssl._create_default_https_context = ssl._create_unverified_context