文件读写

1 txt 读写

A txt读

1 def rfile():
2     f = open('**.txt','r',encoding='UTF-8')   # 中文读加编码格式
3     word_list = list(f.readlines())
4     for i in range(len(word_list)):       
5         word_list[i] = word_list[i].strip()   # 去掉读取的换行,空格
6     return word_list

B txt写

1 def wfile(word):
2     f = open('**.txt','w')
3     f.writelines(word)
4     f.close()

2 excel读写

(参考https://www.cnblogs.com/lingwang3/p/6416023.html)

(参考https://www.cnblogs.com/sun-haiyu/p/7096423.html)

 1 from openpyxl import Workbook
 2 from openpyxl import load_workbook
 3 from openpyxl.writer.excel import ExcelWriter
 4 wb = load_workbook(r"***.xlsx")
 5 # sheet_names = wb.sheetnames
 6 # print(sheet_names)
 7 # sheet_names2 = wb.get_sheet_names()
 8 # print(sheet_names2)
 9 #sheet = wb.get_sheet_by_name(sheet_names2[1])
10 sheet = wb.get_sheet_by_name("Sheet3")
11 for row in sheet.rows:
12     for cell in row:
13         print(cell.value)
14 print('\n')
15 #按列取excel数值
16 for column in sheet.columns:
17     for cell in column:
18         print(cell.value)

 读一行数据:如果要获得某行的数据呢?给其一个索引就行了,因为sheet.rows是生成器类型,不能使用索引,转换成list之后再使用索引list(sheet.rows)[2]这样就获取到第三行的tuple对象。

1 for cell in list(sheet.rows)[0]:
2     print(cell.value)

 

excel写

1  wb = load_workbook(r'**.xlsx')
2 ws = wb.get_sheet_by_name('Sheet')
3 row = ['ling','111'] #写入一行
4 ws.append(row)
5 wb.save(r'**.xlsx')

创建excel并写入

1         w = Workbook()
2         ws = w.active
3         ws.title = "用户名密码"
4         ws.append(pwlist)
5         w.save(r'用户名密码.xlsx')

 

posted @ 2017-12-23 21:57  林雁1983  阅读(115)  评论(0)    收藏  举报