Reading a .txt file line by line in Python

My .txt file looks like this:

! [enter image description here] [1]

How can I read a txt file into a string object that can be printed in the same format as above?

I have tried: 
    with open ("/Users/it/Desktop/Classbook/masterClassList.txt", "r") as myfile:
    data = myfile.read()

for item in data:
    print item

      

This code prints each character on a new line. I need the txt file to be a string for calling string methods, specifically "string.startswith ()"

As you can see, in my IDE console, lines are printed with a black line of spaces between each line of content. How can I remove these blank lines?

Here is my working solution:

with open ("/Users/it/Desktop/Classbook/masterClassList.txt", "r") as myfile:
    data = myfile.read()
    for line in data:
        line.rstrip()

print data

      

+3


source to share


2 answers


The simplest can be:

data = myfile.readlines()

      



This will work with the rest of your code - or you could loop directly to myfile ( inside with

:-) and you will get one line at a time.Note that the lines include the endings \n

, so you might want .strip()

them before printing and c : -)

+4


source


Most efficient way to read lines:

with open ("/Users/it/Desktop/Classbook/masterClassList.txt", "r") as myfile:
    for line in myfile:
        print line

      



i.e. you don't need to read the entire file in memory, only line by line. Here is a link to a python tutorial: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

+6


source







All Articles