一、对txt文本的读写
1、方法一:
使用 with open … as ,可以直接读取和写入,不需要close()
#读取文本test.txt中的内容,存入content中
with open('test.txt','r',encoding='utf-8') as f1:
content=f1.readlines()
#写入指定内容到test文本中
with open('test.txt','a') as file1:
file1.write('扛锄头的农民')
2、方法二:
普通写法,需要使用close()关闭
#普通写法,文件不存在会自动创建,写入文本
f1 = open('text.txt','a',encoding='utf-8')
f1.write('扛锄头的农民')
f1.close()
# 文本的读取
f2 = open('test.txt','r',encoding='utf-8')
content = f2.read()
#把读取到的内容放在变量content里面
f2.close()
二、对excel文件的读写
import openpyxl
#excel写入
wb=openpyxl.Workbook()
sheet=wb.active
sheet.title='我是工作表标题'
sheet['A1']='我是给单元格A1里写入的文字'
rows=[['扛','锄','头','的','农','民']]
#多行写入,使用循环
sheet.append(rows)
wb.save('myexcel.xlsx')
#excel读取
wb=openpyxl.load_wordbook('工作簿名称.xlsx')
sheet=wb['工作表名称']
A1_cell=sheet['A1']
A1=A1_cell.value
print(A1)
三、对csv文件的读写
1、使用with open …as 方法,不需要close()
import csv
#csv文件写入
with open('test.csv','a',newline='',encoding='utf-8') as f1:
writer=csv.writer(f1)
writer.writerow(['扛','锄','头','的','农','民']) #如果有多行,循环写入
#csv文件读取
with open('test.csv','r',newline='',encoding='utf-8') as r1:
reader=csv.reader(f1)
for row in reader:
print(row)
2、一般的写法,需要close()关闭
# csv文件写入
f2=open('test.csv','a',newline='',encoding='utf-8')
writer=csv.writer(f2)
writer.writerow(['扛','锄','头','的','农','民'])
f2.close()
# csv文件读取
r2=open('test.csv','a',newline='',encoding='utf-8')
reader=csv.reader(r2)
for row in reader:
print(row)