python 文件操作, doc, xls, yaml

总结一下文件操作的注意事项

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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值