size 預設為當前位置。當前檔案位置不改變。請注意,如果指定的大小超出檔案的當前大小,其結果是依賴於平台的。
fileObject.truncate( [ size ])
size -- 如果這個可選引數存在,檔案被截斷(最多)為這個大小(size)。
Assuming that 'foo.txt' file contains following text: This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th line
#!/usr/bin/python3 fo = open("foo.txt", "r+") print ("Name of the file: ", fo.name) line = fo.readline() print ("Read Line: %s" % (line)) fo.truncate() line = fo.readlines() print ("Read Line: %s" % (line)) # Close opened file fo.close()
Name of the file: foo.txt Read Line: This is 1s Read Line: []