处理文本(TXT),目录的新建删除,遍历
'''
要了解文件读写模式,需要了解几种模式的区别,以及对应指针
r : 读取文件,若文件不存在则会报错
w: 写入文件,若文件不存在则会先创建再写入,会覆盖原文件
a : 写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾
rb,wb: 分别于r,w类似,但是用于读写二进制文件
r+ : 可读、可写,文件不存在也会报错,写操作时会覆盖
w+ : 可读,可写,文件不存在先创建,会覆盖
a+ : 可读、可写,文件不存在先创建,不会覆盖,追加在末尾
'''
# 写
text = open('text.txt', 'w') # ‘w’,覆盖原有内容
text.write('1\n') # 加入分行,不然会继续写入
text.write('2\n')
text.close() # 文件要先关闭,才能重新打开写入
# 追加 ,with打开能自动关闭文件,读取时光标置于末尾错乱
with open('text.txt', 'a+') as text1:
text1.write('3')
print(text1.readline()) # 打印空
# 读,read(), readline(), readlines()
with open('text.txt', 'r') as text2:
print('......readline()......')
print(text2.readline())
text2.seek(0) # 重置光标(0-文件头,默认值; 1-当前位置; 2-文件尾)
print('......readlines()......')
print(text2.readlines())
text2.seek(0)
print(text2.readlines()[1:2]) # 读取指定行
text2.seek(0)
print('......read()......')
print(text2.read())
text2.seek(0)
for i in text2:
print(':', end=' ')
print(i)
# 读取每一行
print('......读取每一行......')
for line in open('text.txt', 'r'):
print(line[:-1]) # 去掉\n,但是会导致最后一行读取少了一个字符。
# 判断文件是否存在:
import os
if os.path.exists('text.txt'):
print('文件存在~')
# 删除文件
os.remove(filename)
# 删除目录
shutil.rmtree() # 删除目录下文件和子目录,清空内容
os.rmdir()同样的是删除目录
# 创建目录
os.mkdir(path)
# 遍历目录树(不会遍历子目录下的内容,可以用 os.listdir(path)遍历和递归,这个方法也是遍历当前目录的),该方法返回一个元组,包括所有路径名、所有目录列表和文件列表3个元素
for root, dirs, files in os.walk(dir_path):
root 根路径
dirs文件目录
files文件集
# 返回当前的工作目录
getcwd()
处理excel
import xlrd
import xlwt
from xlutils.copy import copy
import os
# 注意对象是工作簿时是用来加载sheet和保存excel,对象是sheet时才是操作cell的(读写改)
# 判断文件是否存在
if os.path.exists('excel.xls'):
pass
else:
# 创建excel
writeExcel = xlwt.Workbook() # 创建工作簿
wx = writeExcel.add_sheet('First Sheet') # 创建sheet页签
wx.write(0, 0, '1') # 行,列,插入的数据
wx.write(0, 1, '2')
wx.write(1, 0, 'A')
wx.write(1, 1, 'B')
writeExcel.save('excel.xls') # 保存excel
# 读取excel
rx = xlrd.open_workbook('excel.xls')
sheet1 = rx.sheet_by_index(0)
cell00 = sheet1.cell(0, 0).value # 获取某个cell的数据
print(cell00)
# 获取整行和整列的数据
row2 = sheet1.row_values(0) # 第1行数据
print(row2)
cols2 = sheet1.col_values(1) # 第2列数据
print(cols2)
# 先读取,再复制,修改后保存
copyRX = copy(rx)
cx = copyRX.get_sheet(0)
cx.write(1, 1, 'B-change')
cx.write(0, 2, '3')
cx.write(1, 2, 'C')
copyRX.save('excel.xls')