Mike
Mike

Reputation: 201

How to convert chars to lines in Python using read method

Noob here. I need to read in a file, using the read (rather than readlines()) method (which provides the input to several functions), and identify all of the lines in that file (i.e. to print or to append to a list).

I've tried join, split, appending to lists, all with little to show.

# Code I'm stuck with:
with open("text.txt", 'r') as file:
    a = file.read()

# Stuff that doesn't work
for line in a:
    # can't manipulate when using the below, but prints fine
    # print(line, end = '')
    temp = (line, end = '')

for line in a:
    temp = '' 
    while not ' ':
    temp += line

new = []
for i in a:
    i = i.strip()

I tend to get either everything in a long string, or 'I', ' ', 't','e','n','d',' ', 't','o' .... get individual chars. I'm just looking to get each line up to the newline char \n, or basically, what readlines() would give me, despite the file being stored in memory using read()

Upvotes: 1

Views: 234

Answers (3)

Mike
Mike

Reputation: 201

With the above help, and using read rather than readlines, I was able to separate out individual lines from a file as follows:

with open("fewwords.txt", "r") as file:
    a = file.read()

empty_list = []

# break a, which is read in as 1 really big string, into lines, then remove newline char
a = a.split('\n')
for i in range(len(a)):
    initial_list.append(a[i])

Upvotes: 0

Slayer
Slayer

Reputation: 882

All you need to do is split the file after reading and you get the list of each line.

with open("text.txt", 'r') as file:
     a = file.read()

a.split('\n')

Upvotes: 1

rdas
rdas

Reputation: 21285

with open('text.txt') as file:
    for line in file:
       # do whatever you want with the line

The file object is iterable over the lines in the file - for a text file.

Upvotes: 3

Related Questions