在Python中操作文件之truncate()方法的使用教程
更新時間:2015年05月25日 09:04:17 投稿:goldensun
這篇文章主要介紹了在Python中操作文件之truncate()方法的使用教程,是Python入門學習中的基礎知識,需要的朋友可以參考下
truncate()方法截斷該文件的大小。如果可選的尺寸參數(shù)存在,該文件被截斷(最多)的大小。
大小默認為當前位置。當前文件位置不改變。注意,如果一個指定的大小超過了文件的當前大小,其結果是依賴于平臺。
注意:此方法不會在當文件工作在只讀模式打開。
語法
以下是truncate()方法的語法:
fileObject.truncate( [ size ])
參數(shù)
size -- 如果可選參數(shù)存在,文件被截斷(最多)的大小。
返回值
此方法不返回任何值。
例子
下面的例子顯示 truncate()方法的使用。
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print "Read Line: %s" % (line)
# Now truncate remaining file.
fo.truncate()
# Try to read file now
line = fo.readline()
print "Read Line: %s" % (line)
# Close opend file
fo.close()
當我們運行上面的程序,它會產(chǎn)生以下結果:
Name of the file: foo.txt Read Line: This is 1st line Read Line:
相關文章
python?動態(tài)導入模塊實現(xiàn)模塊熱更新的方法
這篇文章主要介紹了python?動態(tài)導入模塊,實現(xiàn)模塊熱更新,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
python+selenium+Chrome options參數(shù)的使用
這篇文章主要介紹了python+selenium+Chrome options參數(shù)的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03

