在Python中操作文件之truncate()方法的使用教程
在Python中操作文件之truncate()方法的使用教程
這篇文章主要介紹了在Python中操作文件之truncate()方法的使用教程,是Python入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下
truncate()方法截斷該文件的大小。如果可選的尺寸參數(shù)存在,該文件被截斷(最多)的大小。
大小默認為當(dāng)前位置。當(dāng)前文件位置不改變。注意,如果一個指定的大小超過了文件的當(dāng)前大小,其結(jié)果是依賴于平臺。
注意:此方法不會在當(dāng)文件工作在只讀模式打開。
語法
以下是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()
當(dāng)我們運行上面的程序,它會產(chǎn)生以下結(jié)果:?? ?
Name of the file: foo.txt
Read Line: This is 1st line
?
Read Line:
轉(zhuǎn)載于:https://www.cnblogs.com/amengduo/p/9586581.html
總結(jié)
以上是生活随笔為你收集整理的在Python中操作文件之truncate()方法的使用教程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 海南热带海洋学院交了电费什么时候有电
- 下一篇: React-Native系列Androi