标签:pycha 关系 信息 work users name active 不可 utf-8
1、读、写、追加文件
读:打开文件 r 读写:r+
写:w 可写不可读 清空原文件 写读:w+ 清空文件
追加:a+ 可以读写,文件不存在自动创建
练习读txt文件类容:
#-*- coding : utf-8 -*-
file = open(r‘C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡树.txt‘)
with file:
data = file.read()
print(data)
读取excel文件类容:
读取Excel是需要模块openpyxl:
关闭文件操作: file.close()
文件句柄的关系,open过后需要关闭
读取文件一行信息:file.readline()
读取文件全部信息信息:file.readlines()
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
‘‘‘
@project:
@name: test_excel
@date: 2019/12/4 11:51
‘‘‘
from openpyxl import load_workbook
import openpyxl
def main(path_url=r"D:\untitled\test\700URLV1.xlsx"):
L = []
workbook = load_workbook(path_url) # 找到需要xlsx文件的位置
booksheet = workbook.active # 获取当前活跃的sheet,默认是第一个sheet
for row in booksheet.rows:
for col in row:
if col.value:
L.append(col.value)
return L
if __name__ == ‘__main__‘:
print(main())
文件写入类容操作练习:
#-*- coding : utf-8 -*-
file = open(‘C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡树.txt‘,‘w‘)
for i in range(20):
file.write(str(i))
file.close()
file = open(‘C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡树.txt‘,‘r‘)
print(file.read())
file.close()
创建文件 操作:
写入文件,换行操作:运用"\n"
#-*- coding : utf-8 -*-
file = open(‘C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡.txt‘,‘w‘)
for i in range(5):
file.write(str(i) + ‘\n‘)
file.close()
file = open(‘C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡.txt‘,‘r‘)
print(file.read())
file.close()
标签:pycha 关系 信息 work users name active 不可 utf-8
原文地址:https://www.cnblogs.com/zhangqinANDwangjiasen/p/12073137.html