Latest web development tutorials

Python3 truncar File () método

Python3 Arquivo método (File) Python3 Arquivo método (File)


esboço

truncar () método é usado para truncar o arquivo, se você especificar o tamanho parâmetro opcional, disse caracteres de tamanho de arquivo truncado.Se você não especificar um tamanho, em seguida, redefinir para o local atual.

gramática

truncar () método tem a seguinte sintaxe:

fileObject.truncate( [ size ])

parâmetros

  • tamanho - Como alternativa, se o arquivo existe truncados para bytes de tamanho.

Valor de retorno

Este método não tem valor de retorno.

Exemplos

O exemplo a seguir demonstra o método usar TRUNCATE ():

arquivo de conteúdo W3big.txt da seguinte forma:

1:www.w3big.com
2:www.w3big.com
3:www.w3big.com
4:www.w3big.com
5:www.w3big.com

Loop lê o conteúdo do ficheiro:

#!/usr/bin/python3

fo = open("w3big.txt", "r+")
print ("文件名: ", fo.name)

line = fo.readline()
print ("读取行: %s" % (line))

fo.truncate()
line = fo.readlines()
print ("读取行: %s" % (line))

# 关闭文件
fo.close()

O exemplo acima saída é:

文件名:  w3big.txt
读取行: 1:www.w3big.com

读取行: ['2:www.w3big.com\n', '3:www.w3big.com\n', '4:www.w3big.com\n', '5:www.w3big.com\n']

Os exemplos a seguir interceptação 10 bytes w3big.txt arquivo:

#!/usr/bin/python3

# 打开文件
fo = open("w3big.txt", "r+")
print ("文件名为: ", fo.name)

# 截取10个字节
fo.truncate(10)

str = fo.read()
print ("读取数据: %s" % (str))

# 关闭文件
fo.close()

O exemplo acima saída é:

文件名为:  w3big.txt
读取数据: 1:www.runo

Python3 Arquivo método (File) Python3 Arquivo método (File)