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

Asked

Viewed 513 times

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 read each line of file into an item of a list or tuple?

There is a simple way as it is done in PHP?

2 answers

2

Do it like 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, tabs from the end/start of the line do:

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

Or just remove line breaks (\n):

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

2

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

Behold:

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

Simple and in a row!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.