0

I am trying to extract data from a text file. I convert the text file from byte to string, as per the code below.

I want to extract specific data from the file. For that, if I read the file by using, for line in data2: print(line) it is reading each character, not per word or per line. For example, instead of printing the full line it is printing each character as a line.

How can I read by line instead of by character?

data = urllib.request.urlopen('http://lib.stat.cmu.edu/datasets/boston')
data1 = data.read()
data2 = data1.decode("utf-8")
  • Possible duplicate of [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – gillesB Feb 04 '19 at 11:24

2 Answers2

0

There are several ways, you could do this.

data = urllib.request.urlopen('http://lib.stat.cmu.edu/datasets/boston')
data1 = data.read()
data2 = data1.decode("utf-8")
for line in data2.split('\n'):
  print(line)

or 

data = urllib.request.urlopen('http://lib.stat.cmu.edu/datasets/boston')
for line in data:
  print(line.strip())
han solo
  • 6,390
  • 1
  • 15
  • 19
0

After the convertion you have a long string. Just split it at position "\n" and output every line

listOfLines = data2.split('\n')
for line in listOfLines:
    print(line)
DerMann
  • 223
  • 1
  • 2
  • 13