Jump to content

Aceder a determinada linha no ficheiro


Guest yyajsayy

Recommended Posts

Olá Boa tarde a todos.

Alguém me sabe dizer se tendo um ficheiro de texto na forma por exemplo:

2

4

5

6

7

89

0

4

3

11

5

7

Consigo após abrir o ficheiro open()...

Aceder diretamente a alguma linha, ou terei de percorrer todas as linha para chegar ao valor desejado?

Por exemplo, quero que ao abrir o ficheiro aceder logo ao valor 89. É possível?

Abraço.

Link to comment
Share on other sites

Segundo a documentação sim, mas não funciona por linhas e sim por bytes. Tens o link um pouco abaixo nesta resposta. Agora consoante a tua necessidade é bem provável que tenhas soluções mais "elegantes" e certamente mais fáceis de usar. Os binários numpy, a título de exemplo, são extremamente rápidos de carregar para a memória mesmo se um ficheiro tiver centenas de megas.

Tens o seguinte exemplo na página:

http://docs.python.org/tutorial/inputoutput.html

>>> f = open('/tmp/workfile', 'r+')

>>> f.write('0123456789abcdef')

>>> f.seek(5) # Go to the 6th byte in the file

>>> f.read(1)

'5'

>>> f.seek(-3, 2) # Go to the 3rd byte before the end

>>> f.read(1)

'd'

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.