Python Berkas truncate () metode
garis besar
Metodememotong () digunakan untuk memotong file, jika Anda menentukan ukuran parameter opsional, kata karakter ukuran file terpotong.Jika Anda tidak menentukan ukuran, terputus dari posisi saat ini, semua karakter di belakang ukuran setelah pemotongan dihapus.
tatabahasa
Metode memotong () memiliki sintaks berikut:
fileObject.truncate( [ size ])
parameter
Ukuran - Atau, jika file ada dipotong untuk byte ukuran.
Kembali Nilai
Metode ini tidak memiliki nilai kembali.
contoh
Contoh berikut menunjukkan metode penggunaan truncate ():
File konten W3big.txt sebagai berikut:
1:www.w3big.com 2:www.w3big.com 3:www.w3big.com 4:www.w3big.com 5:www.w3big.com
Lingkaran membaca isi dari file:
#!/usr/bin/python # -*- coding: UTF-8 -*- # 打开文件 fo = open("w3big.txt", "r+") print "文件名为: ", fo.name line = fo.readline() print "读取第一行: %s" % (line) # 截断剩下的字符串 fo.truncate() # 尝试再次读取数据 line = fo.readline() print "读取数据: %s" % (line) # 关闭文件 fo.close()
Contoh di atas output:
文件名为: w3big.txt 读取第一行: 1:www.w3big.com 读取数据:
Contoh berikut intersepsi 10 bytes w3big.txt berkas:
#!/usr/bin/python # -*- coding: UTF-8 -*- # 打开文件 fo = open("w3big.txt", "r+") print "文件名为: ", fo.name # 截取10个字节 fo.truncate(10) str = fo.read() print "读取数据: %s" % (str) # 关闭文件 fo.close()
Contoh di atas output:
文件名为: w3big.txt 读取数据: 1:www.runo