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

一、课程目标

了解读写文件的基本操作

使用第三方包读写wordexcel文件

二、详情解读

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

相关内容

热门资讯

美民调:超半数美国人称生活成本... 据凤凰卫视报道,美国政治新闻网5月29日公布的最新民调显示,美国选民仍然不满意总统特朗普的经济政策,...
燃气灶开关无法控制怎么办 燃气灶开关无法控制,这是一种非常危险的情况。这种情况可能会导致燃气泄漏和火灾等严重后果。如果您遇到这...
为什么海尔冰箱冷冻室温度显示一... 这种情况表示的是超温报警灯亮了。也就是说冰箱的冷冻室温度没有降下去,冷冻室温度降到零下8度左右就自动...
西门子冰箱冷冻室温度一直闪烁是... 1、有可能是因为操作不当导致的情况;2、有可能是西门子冰箱显示屏的供电电源或显示屏本身的故障。 ...
冰雪儿点菜柜冷冻室温度灯一直闪 1、可能是因为冰雪儿点菜柜的压缩机遭到了损坏。 2、可能是因为点菜柜的内部电路发生了断路。3、可能是...
海尔冰箱冷冻温度一直闪怎么解决 一直闪可能是超温报警灯亮了,这说明冷冻室的温度出现了异常,一般是温度过高造成的报警,看看冷冻室是否关...
健康证上标注“女性私密”?越界... 南方都市报29日报道,深圳一市民陈某(化名)在深圳市南山区妇幼保健院办理托幼岗位健康证时遭遇乱象。据...
2026香格里拉对话会开幕,中... 第23届香格里拉对话会5月29日晚在新加坡开幕,来自40多个国家和地区的政要、防务官员和专家学者等共...
美国中期选举:谁是骄兵必败,谁... 【文/观察者网专栏作者 周德宇】从特朗普二次执政以来,其民调可以说是一路雪崩,连累着共和党也一起遭殃...
芗城区科协开展全国科技工作者日... 5月27日,芗城区科协联合东铺头街道、瑞京社区等单位,走进芗城实幼东铺头园区,开展芗城区全国科技工作...