-3

I have the following code:

test_file = open("test.txt","r")
line1 = test_file.readline(1)
test_file.close()
line1 = int(line1)
print(line1)

I have 12 written into the file.

I simply get the output 1.

Can someone please explain what is wrong with this code?

francisco
  • 37
  • 4

3 Answers3

2

The function readline() has no parameter for reading a special line. It reads from the file line-by-line for each call. To read just the first line call the function one time like:

line1 = test_file.readline()
micharaze
  • 957
  • 8
  • 25
  • You can call it in a `for` loop and increment an index. When the index is reached a specific number you have the specific line you want. – micharaze Sep 24 '19 at 08:40
1

You have passed the size to read in your code. It read the bytes accordingly to passed size in readline method

Also use with to open file (in pythonic way)

with open("test.txt","r") as test_file:
    line1 = test_file.readline()
    line1 = int(line1)
print(line1)
Saleem Ali
  • 1,363
  • 11
  • 21
0

When you specify 1, you are telling readline() to take only the first character in your line, it's better to do this update on your code:

test_file = open("test.txt","r")
line1 = test_file.readline() # Remove the indice 1
test_file.close()
line1 = int(line1)
print(line1)

Or in one line like this:

print(int(open("test.txt","r").readline()))
Sanix darker
  • 105
  • 2
  • 5