How to Read a File Line-By-Line into a List

Reading a text file line by line and converting it into a list using only read()?

You can use split():

def get_list1(text):
result=[]
for row in text:
result.append(row)
return result

with open("test.txt") as f:
n = f.read().split("\n")

l=get_list1(n)
print(l)

Or just use splitlines()

def get_list1(text):
result=[]
for row in text:
result.append(row)
return result

with open("test.txt") as f:
n = f.read().splitlines()

l=get_list1(n)
print(l)

Read the file line-by-line and use the split() function to break the line into a list of integers using python

with this "tiny.txt":

5 
0 1
1 2 1 2 1 3 1 3 1 4
2 3
3 0
4 0 4 2

and this code:

def adjMatrixFromFile(file):
Our_numbers = []
file = open(file, 'r')
line = file.readlines()

for i in line:
i=i.replace('\n','') #remove all \n
numbers = i.split(' ')
numbers = filter(None, numbers) #remove '' in the list
Our_numbers.extend(numbers) #add values from a list to another list

Our_numbers = [int(i) for i in Our_numbers] #convert all element str -> int
return Our_numbers

print(adjMatrixFromFile("tiny.txt"))

I got this output:

[5, 0, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 2, 3, 3, 0, 4, 0, 4, 2]

Reading a File Line by Line in Python

If the idea here is to understand how to read a file line by line then all you need to do is:

with open(filename, 'r') as f:
for line in f:
print(line)

It's not typical to put this in a try-except block.

Coming back to your original code there are several mistakes there which I'm assuming stem from a lack of understanding of how classes are defined/work in python.

The way you've written that code suggests you perhaps come from a Java background. I highly recommend doing one of the myriad free and really good online python courses offered on Coursera, or EdX.


Anyways, here's how I would do it using a class:

class ReadFile:
def __init__(self, path):
self.path = path

def print_data(self):
with open(self.path, 'r') as f:
for line in f:
print(line)

if __name__ == "__main__":
reader = ReadFile("H:\\Desktop\\TheFile.txt")
reader.print_data()

reading in text file as string list in python

it is possible to insert the strings in the text file in to an array d eliminated with newline character. like below

a = open('mytextfile.txt')
b=a.split('\n'))
array=[]
for texts in b:
array=array.add(text)

then you can get your favorite string

fav=array[4]

read from file line by line , multiple match in file possible

Here is the shorter version:

list_planes = []
list_temperatures = []
[list_planes.append([sub.split()[0] for sub in content]) for content in list_lines]
[list_temperatures.append([sub.split()[1] for sub in content]) for content in list_lines]

list_planes_r, list_planes_f = list_planes
temp_plane_r, temp_plane_f = list_temperatures


Related Topics



Leave a reply



Submit