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