How to open file separating each line in an item from a list / tuple?

2

In PHP, we have a function called file which, when opening a file, causes each line to be placed in an item of a array .

Example:

hello.txt

   olá
   mundo

php script

file('hello.txt'); // array('olá', 'mundo')

In Python, how could I do to read each line of file in an item of a list or tuple ?

Is there a simple way to do it in PHP?

    
asked by anonymous 23.03.2017 / 17:51

2 answers

2

There is an answer I saw in Stackoverflow English which is simply fantastic.

See:

 lines = tuple(open('hello.txt', 'r'))

Simple and in a row!

    
23.03.2017 / 17:56
2

Do this:

with open('file.txt', 'r') as f:
    list_lines = f.readlines() # ['  1 linha  \n', '  2 linha  \n' ...]

To remove line breaks and / or extra spaces, end / beginning line tabs do:

with open('file.txt', 'r') as f:
    list_lines = [i.strip() for i in f] # ['1 linha', '2 linha' ...]

Or remove only line breaks ( \n ):

with open('file.txt', 'r') as f:
    list_lines = f.read().splitlines() # ['  1 linha  ', '  2 linha  ' ...]
    
23.03.2017 / 17:53