五月综合缴情婷婷六月,色94色欧美sute亚洲线路二,日韩制服国产精品一区,色噜噜一区二区三区,香港三级午夜理伦三级三

您現(xiàn)在的位置: 365建站網(wǎng) > 365文章 > Python 文件 truncate() 方法(截斷返回截取長度)

Python 文件 truncate() 方法(截斷返回截取長度)

文章來源:365jz.com     點擊數(shù):1250    更新時間:2018-09-20 08:37   參與評論

概述

Python 文件 truncate() 方法用于截斷文件并返回截斷的字節(jié)長度。

指定長度的話,就從文件的開頭開始截斷指定長度,其余內(nèi)容刪除;不指定長度的話,就從文件開頭開始截斷到當前位置,其余內(nèi)容刪除。

語法

truncate() 方法語法如下:

1

fileObject.truncate([size])

參數(shù)

  • size -- 可選,如果存在則文件從開頭截斷為指定字節(jié)。

返回值

該方法沒有返回值。

實例

以下實例演示了 truncate() 方法的使用:

文件 365jz.txt 的內(nèi)容如下:

1

2

3

4

5

1:theartemis.cn

2:theartemis.cn

3:theartemis.cn

4:theartemis.cn

5:theartemis.cn

循環(huán)讀取文件的內(nèi)容:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#!/usr/bin/python3

 

fo = open("365jz.txt", "r+", encoding="utf-8")

# print ("文件名: ", fo.name)

 

fo.seek(36)

fo.truncate()  # 從第36個字節(jié)以后的內(nèi)容全部刪除了

fo.seek(0,0)

line = fo.readlines()

print("讀取行: %s" % (line))

fo.truncate(10)  # 截取10個字節(jié)

fo.seek(0,0)

str = fo.read()

print("讀取數(shù)據(jù): %s" % (str))

 

# 關閉文件

fo.close()

以上實例輸出結果為:

1

2

3

文件名:  365jz.txt

讀取行: ['1:theartemis.cn\n', '2:theartemis.cn\n']

讀取數(shù)據(jù): 1:www.365j


假設’foo.txt‘文件中包含以下行 -

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th lineShell

以下示例顯示了truncate()方法的用法。

#!/usr/bin/python3fo = open("foo.txt", "r+")print ("Name of the file: ", fo.name)line = fo.readline()print ("Read Line: %s" % (line))pos=fo.tell()print ("current position : ",pos)# Close opened filefo.close()Python

執(zhí)行上面代碼后,將得到以下結果 -

Name of the file:  foo.txt
Read Line: This is 1s
Read Line: []


如對本文有疑問,請?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會為你解答?。?點擊進入論壇

發(fā)表評論 (1250人查看,0條評論)
請自覺遵守互聯(lián)網(wǎng)相關的政策法規(guī),嚴禁發(fā)布色情、暴力、反動的言論。
昵稱:
最新評論
------分隔線----------------------------

其它欄目

· 建站教程
· 365學習

業(yè)務咨詢

· 技術支持
· 服務時間:9:00-18:00
365建站網(wǎng)二維碼

Powered by 365建站網(wǎng) RSS地圖 HTML地圖

copyright © 2013-2024 版權所有 鄂ICP備17013400號