Python study notes: read and write files

First, the curriculum objectives

Learn the basics of reading and writing files

The use of third-party packages to read and write Word , Excel file

Second, the details of interpretation

01. basic operations:

# Interactive mode:

>>> f = open ( 'raise.txt' , 'w') # open the current working directory raise.txt file, if the file does not exist, create

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

16 # write the contents of the file size

>>> f.close () # perform this step to be considered saved to a file

 

>>> import os

>>> os.getcwd () # to view the current working directory

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

>>> os.listdir () # file and view the files in the current working directory folder

['raise.txt']

 

>>> f = open ( 'raise.txt' ) # open the file in read-only mode

>>> f.read () # read the file contents

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

 

# Write to the file content with context manager way, you can not perform the close () operation.

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

 

# View content just written

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

>>> for line in f: # here f is iterables

...     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()

'  # At this time the file pointer points to the end of file has, and then read on an empty string

 

# To operate the file pointer location, can seek () function

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

Guess you like

Origin blog.51cto.com/14511863/2458039