总结一下文件操作的注意事项
yaml
这个也经常用于配置文件,记录一下一些高级的用法
yaml 文件 测试一下覆盖的情况,基本说明在下面的会覆盖上面的
sec1: &sec1
subsec1: nihao
subsec1: good
subsec2: 你好
subsec3: 打开保护你的降落伞
sec2:
<<: *sec1
subsec2: 明天你好
python 代码及结果
print( cfg.sec1.subsec1 )
print( cfg.sec2.subsec2 )
print( cfg.sec2.subsec3 )
good
明天你好
打开保护你的降落伞
doc
设置页边距
import docx
from docx.shared import Inches, Cm
fin="data/read.txt"
fout="data/read.docx"
doc=docx.Document()
sections = doc.sections
for section in sections:
section.top_margin = Cm(0.5)
section.bottom_margin = Cm(0.5)
section.left_margin = Cm(1)
section.right_margin = Cm(1)
for i, e in enumerate(readlines(fin)): # readlines 这个函数没有
doc.add_paragraph( f"{i+1}\n{e}" )
doc.save(fout)
xls
写
import xlwt
workbook=xlwt.Workbook(encoding='utf-8')
booksheet=workbook.add_sheet('txt2excel', cell_overwrite_ok=True)
# 第一个表示 row, col, value
for i, v in enumerate(arr):
booksheet.write(0,i,v)
workbook.save(fexcel)
读
import xlrd
data = xlrd.open_workbook("vtts_test.xls")
table = data.sheets()[0] #通过索引顺序获取
#table = data.sheet_by_index(sheet_indx) #通过索引顺序获取
#table = data.sheet_by_name(sheet_name) #通过名称获取
arr=[]
print( table.nrows, table.ncols )
for c in range(table.ncols):
for r in range(1, table.nrows):
#print(table.cell(r,c), table.cell(r,c).ctype)
if table.cell_type(r,c)==1:
#print(table.cell_value(r,c))
arr.append(table.cell_value(r,c))