Python學(xué)習(xí)筆記:讀寫文件

一、課程目標(biāo)

創(chuàng)新互聯(lián)是專業(yè)的郫都網(wǎng)站建設(shè)公司,郫都接單;提供網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站建設(shè),網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行郫都網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!

了解讀寫文件的基本操作

使用第三方包讀寫word、excel文件

二、詳情解讀

01.基本操作:

# 交互模式下:

>>> f = open('raise.txt', 'w') # 打開當(dāng)前工作目錄下的raise.txt文件,如果文件不存在,則創(chuàng)建

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

16 ?# 寫入文件的內(nèi)容大小

>>> f.close() # 執(zhí)行到這一步才算保存到文件中

?

>>> import os

>>> os.getcwd() # 查看當(dāng)前工作目錄

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

>>> os.listdir() # 查看當(dāng)前工作目錄下的文件和文件夾

['raise.txt']

?

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

>>> f.read() # 讀取文件內(nèi)容

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

?

# 用上下文管理器的方式寫入文件內(nèi)容,可以不用執(zhí)行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

?

# 查看剛剛寫入的內(nèi)容

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

>>> for line in f: ?# 此處f是可迭代對(duì)象

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

'' ?# 此時(shí)文件指針已經(jīng)指向文件末尾了,再往下讀則為空字符串

?

# 要想操作文件指針指向的位置,可用seek()函數(shù)

>>> 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) # 將文件指針移動(dòng)到開始位置

0

>>> f.read(3) # 從文件開始位置向后讀取3個(gè) 字符

'You'

>>> f.readline() # 從指針?biāo)谖恢米x到行末

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

>>> f.readlines() # 從指針?biāo)谖恢弥鹦凶x取內(nèi)容,返回列表,一行作為列表的一個(gè)元素

['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() # 實(shí)例化一個(gè)Document對(duì)象

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

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

>>> d.save('python.docx') # 保存,執(zhí)行到這一步才算保存到文件中

>>> import os

>>> os.listdir()

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

?

>>> f = open('python.docx', 'rb') # 以只讀二進(jìn)制模式打開文件

>>> doc = Document(f)

>>> doc

<docx.document.Document object at 0x02803E40>

>>> doc.paragraphs

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

>>> for i in doc.paragraphs: # 逐行循環(huán)打印出python.docx文件的內(nèi)容

function(){ //MT4買賣價(jià) 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
用上式安裝失敗的同學(xué)可以用這個(gè):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') # 創(chuàng)建一個(gè)新的工作表

>>> ws1.title ??# ws1工作表的名稱

'rust'

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

['python', 'rust']

?

# 往工作表中寫入數(shù)據(jù)

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

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

<Cell 'python'.B2>

>>> wb.save('excel.xlsx') # 將數(shù)據(jù)保存到excel.xlsx中

分享名稱:Python學(xué)習(xí)筆記:讀寫文件
URL鏈接:http://bm7419.com/article4/gigpie.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站、標(biāo)簽優(yōu)化響應(yīng)式網(wǎng)站、面包屑導(dǎo)航、微信公眾號(hào)、網(wǎng)站導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名