python基础文件读写

读写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')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值