Joe Hunter
Joe Hunter

Reputation: 21

Reading each line from text file

I have a script which reads each line from text file. but somehow it prints all at once. I want to run one line end and run next. here is the code.

f = open('textfile.txt', 'r')
    file= f.read()   
    for x in file:
        print(x, file.strip())
        comSerialPort.write(x.encode('utf-8'))

Upvotes: 1

Views: 42

Answers (2)

Rakesh
Rakesh

Reputation: 82755

Use with statement and then iterate lines.

Ex:

with open('textfile.txt', 'r') as infile:
    for line in infile:
        print(line)
        comSerialPort.write(line.strip().encode('utf-8'))

Note: read() reads the entire content of the file.

Upvotes: 0

locke14
locke14

Reputation: 1375

Use readlines instead of read

with open('textfile.txt', 'r') as f:
    lines = f.readlines()
    for line in lines:
        print(line)
        # do stuff with each line

Upvotes: 3

Related Questions