0

I just want my program to read a line in my file, do something with text in line, then move onto the next line, until all lines in the file are finished.

Here's what I have so far:

with open(str(filepath), r) as fp:
    for line in fp:
        rdline = fp.readline() 
        doSomething(rdline)

this isn't working however. How should I approach this? I don't want to convert all lines into a dictionary or list, as I will be working with files with a large amount of lines.

Mave
  • 81
  • 1
  • 1
  • 9
  • You don't need that `rdline = fp.readline()` since you're already iterating over fp on that for loop. Just `doSomething(line)`. – accdias Feb 13 '20 at 02:22
  • Does this answer your question? [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) – AMC Feb 13 '20 at 02:51

3 Answers3

2

Try this:

with open('filepath') as infile:
  for row in infile:
    do_somthing(row.strip())

Bye

1

As I said in my comment, that rdline = fp.readline() is not necessary since you are already iterating over fp on your for loop.

with open(filepath) as f:
    for line in f: 
        do_something(line)
accdias
  • 5,160
  • 3
  • 19
  • 31
0

The error I think, that have appeared in your code is

with open(str(filepath), 'r') as fp:
    lines = fp.readlines() 
    for line in lines:
        do_something(line)

give the open function second parameter as a string.

(or)

If the file size is large you can go by this approach

with open(str(filepath), 'r') as fp:
    line = fp.readline() 
    while line:
        do_something(line)
        line = fp.readline()
Praveen Kumar
  • 91
  • 1
  • 5
  • this is true, but it still doesn't solve my problem. thanks for pointing it out though! – Mave Feb 13 '20 at 02:39