Home python Reading a file line by line in Python

Reading a file line by line in Python

Author

Date

Category

Hello. The txt file contains:

97
115
116

Each number is written on a new line. I wanted to create a variable or an array containing a number, but the trivial a = f.read () does not help, since it reads the entire file in integer. Help please)


Answer 1, authority 100%

Apparently you were too lazy to read about reading files in python, because right after file.read () , textbooks usually talk about file.readline () and file .readlines ()
Therefore, you have 3 options:

  1. Read the file line by line in a loop through file.readline ()
  2. Read the entire file at once into a list via file.readlines () , but then you yourself have to get rid of linefeed characters
  3. Read the entire file at a time and process it through splitlines () file.read (). splitlines () – also immediately into the list and without line feeds .

The last option is the most attractive, in my opinion:

with open ('numbers.txt', 'r') as f:
  nums = f.read (). splitlines ()
print (nums)

[’97’, ‘115’, ‘116’]


Answer 2, authority 44%

test.txt

97
115
116

with open ('test.txt') as f:
  myList = [line.split () for line in f]
print (myList)
[['97'], ['115'], ['116']]
flatList = [item for sublist in myList for item in sublist]
print (flatList)
['97', '115', '116']

Answer 3, authority 22%

with open ("file.txt") as file:
  str = [row.strip () for row in file]

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions