Python学习笔记:读写文件

一、课程目标

了解读写文件的基本操作

使用第三方包读写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.') # 添加段落

<docx.text.paragraph.Paragraph object at 0x0280D2F0>

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

>>> import os

>>> os.listdir()

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

 

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

>>> doc = Document(f)

>>> doc

<docx.document.Document object at 0x02803E40>

>>> doc.paragraphs

[<docx.text.paragraph.Paragraph object at 0x0280D710>]

>>> 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')

<docx.shape.InlineShape object at 0x00851F70>

>>> 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

<Cell 'python'.B2>

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

猜你喜欢

转载自blog.51cto.com/14511863/2458039
今日推荐