Python学习笔记:读写文件
admin
2023-06-26 17:41:54
0次

一、课程目标

了解读写文件的基本操作

使用第三方包读写word、excel文件

二、详情解读

01.基本操作:

# 交互模式下:

>>> f = open('raise.txt', 'w') # 打开当前工作目录下的 raise.txt 文件,如果文件不存在,则创建

>>> f.write('You raise me up.')

16  # 写入文件的内容大小

>>> f.close() # 执行到这一步才算保存到文件中

 

>>> import os

>>> os.getcwd() # 查看当前工作目录

'F:\\06python\\00pythonfullstackengineer\\chapter03'

>>> os.listdir() # 查看当前工作目录下的文件和文件夹

['raise.txt']

 

>>> f = open('raise.txt') # 以只读模式打开文件

>>> f.read() # 读取文件内容

'You raise me up.'

 

>>> dir(f)

['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '_

_doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattrib

ute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '

__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '_

_reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclassho

ok__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_f

inalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno

', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'rea

dable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'tru

ncate', 'writable', 'write', 'write_through', 'writelines']

 

# 用上下文管理器的方式写入文件内容,可以不用执行close()操作。

>>> with open('raise.txt', 'a') as f:

...     f.write(' so I can stand on mountains. \nYou raise me up to walk on stor

my sea. \nI am strong when I am on your shoulders.')

...

111

 

# 查看刚刚写入的内容

>>> f = open('raise.txt')

>>> for line in f:  # 此处 f 是可迭代对象

...     print(line, end='')

...

You raise me up. so I can stand on mountains.

You raise me up to walk on stormy sea.

I am strong when I am on your shoulders.>>>

>>>

>>> f.read()

''  # 此时文件指针已经指向文件末尾了,再往下读则为空字符串

 

# 要想操作文件指针指向的位置,可用 seek() 函数

>>> help(f.seek)

Help on built-in function seek:

 

seek(cookie, whence=0, /) method of _io.TextIOWrapper instance

    Change stream position.

 

    Change the stream position to the given byte offset. The offset is

    interpreted relative to the position indicated by whence.  Values

    for whence are:

 

    * 0 -- start of stream (the default); offset should be zero or positive

    * 1 -- current stream position; offset may be negative

    * 2 -- end of stream; offset is usually negative

 

    Return the new absolute position.

>>> f.seek(0) # 将文件指针移动到开始位置

0

>>> f.read(3) # 从文件开始位置向后读取 3个 字符

'You'

>>> f.readline() # 从指针所在位置读到行末

' raise me up. so I can stand on mountains. \n'

>>> f.readlines() # 从指针所在位置逐行读取内容,返回列表,一行作为列表的一个元素

['You raise me up to walk on stormy sea. \n', 'I am strong when I am on your sho

ulders.']

02.特定类型文件:

1).word: pip install python-docx

# 交互模式下:

>>> from docx import Document

>>> d = Document() # 实例化一个Document对象

>>> d.add_paragraph('Life is short, You need Python.') # 添加段落

>>> d.save('python.docx') # 保存,执行到这一步才算保存到文件中

>>> import os

>>> os.listdir()

['python.docx', 'raise.txt']

 

>>> f = open('python.docx', 'rb') # 以只读二进制模式打开文件

>>> doc = Document(f)

>>> doc

>>> doc.paragraphs

[]

>>> for i in doc.paragraphs: # 逐行循环打印出python.docx文件的内容

function(){ //MT4买卖价 http://www.fx61.com/faq/muniu/436.html

...     print(i.text)

...

Life is short, You need Python.

 

# 在world添加图片

>>> d.add_picture('laoqi.jpg')

>>> d.save('python.docx') # 注意图片是按原始大小放入word文档的

.excel: pip install openpyxl
用上式安装失败的同学可以用这个:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple openpyxl

# 交互模式下:

>>> from openpyxl import Workbook

>>> wb = Workbook()

>>> ws = wb.active # 获取工作薄里的工作表

>>> ws.title # 获取工作表的名称

'Sheet'

>>> ws.title = 'python' # 修改工作表的名称

>>> ws1 = wb.create_sheet('rust') # 创建一个新的工作表

>>> ws1.title   # ws1工作表的名称

'rust'

>>> wb.sheetnames # 工作表的所有表的表名

['python', 'rust']

 

# 往工作表中写入数据

>>> ws['E1'] = 123  # 第E列第1行写入 123

>>> ws.cell(row=2, column=3, value=111) # 第2行第3列写入 111

>>> wb.save('excel.xlsx') # 将数据保存到 excel.xlsx 中

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...