读写txt
import os
# 返回当前目录
os.getcwd()
f = open('test.txt','w')
f.write('life is short,you need python')
# 没有close都是在内存里,close之后保存了
f.close()
对于open函数常用的打开方式
# 默认是r
f = open('test.txt')
f.read()
dir(f)
#使用with可以不用f.close()就保存
with open('test.txt','a') as f:
f.write('\nhello word')
f = open('test.txt')
for line in f:
print(line,end='')
#将指针归0
f.seek(0)
for line in f:
print(line,end='')
读写csv
import csv
data =[['name','number'],['python',111],['java',222],['php',333]]
print(data)
with open('csvfile.csv','w',newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
f = open('csvfile.csv')
reader = csv.reader(f)
for row in reader:
print(row)
在写的时候遇到了一个坑,open('csvfile.csv','w',newline='')这个如果最后不加newline参数的话默认会换行。
读写excel用的openpyxl
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title
ws.title = 'python'
ws.title
ws2 = wb.create_sheet('java')
ws2.title
wb.sheetnames
ws['E1'] = 111
ws.cell(row=2,column=2,value=222)
wb.save('example.xlsx')