本节扩展了之前学过的文件操作,介绍了csv文件,JSON文件,Excel文件,之后又学习在Python中是如何对这三种文件进行读写操作,主要使用到了三个模块csv模块、json模块、xlrd和xlwt模块并介绍了其中简单的方法。
1.文件操作基础
复习一下最简单的文件读写操作,open,write
def txt_writer():
"""写文件"""
with open('date.txt','w',encoding='utf-8') as f: #创建打开txt
f.write('禹荀知识产权')
lines = [
'地址:南昌市\n',
'QQ:179371292\n',
'网址:www.ncyxipr.cn\n'
]
f.writelines(lines)
if __name__ =='__main__':
txt_writer()
运行结果创建txt,文件成功
def txt_writer():
"""写文件"""
with open('date.txt','w',encoding ='utf-8') as f: #创建打开txt
f.write('禹荀知识产权')
lines = [
'地址:南昌市\n',
'QQ:179371292\n',
'网址:http://www.ncyxipr.cn/\n'
]
f.writelines(lines)
def txt_read():
"""读文件 """
with open('date.txt',encoding ='utf-8') as f: #读取txt文件
for line in f:
print(line, end = ' ') #前面已经加了换行,end=改变一下格式不然就会2行空格
if __name__ =='__main__':
txt_read()
运行结果
禹荀知识产权地址:南昌市
QQ:179371292
网址:www.ncyxipr.cn