0

Hi I am trying to read data from a text file, line by line. However I am having problems with the output of the last line.

The text file I have created is:

position 50 10
line 50 0
line -50 0
line 0 -50

Here is my code:

f = open("temp.txt","r")

line = f.readline()
while line != "":
	line = line[:-1]
	print line
	data = split(line, " ")
	line = f.readline()

I get the following output:

position 50 10
line 50 0
line 0 50
line -50 90
line 0 -5

For some reason the last 0 keeps getting cut off.


I've also tried:

f = open("temp.txt","r")


for line in f:
	print line,
	data = split(line, " ")

This seems to give me the correct output but I don't want to print each line.

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by axa121
1

Try
line = line.strip() ## instead of line = line[:-1]
or make sure there is a return/newline in the last line of the file.

0

Try
line = line.strip() ## instead of line = line[:-1]
or make sure there is a return/newline in the last line of the file.

Thanks I'm silly I never checked for that. I had it working before but I edited the file afterwards and it stopped working.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.