0

I have a text file in the same directory labelled test.txt. It contains the following 3 lines:

10
3
5

The output this gives me is:

1
0

3

My code is below.

f = open('test.txt',"r")
test1 =(f.readline(1))
test2 = (f.readline(2))
test3 = (f.readline(3))
print (test1)
print (test2)
print (test3)

How would i go about making it pick up the full variables? Ie test1 = 10, test2=3, test3 = 5? Very new to python :(

4
  • 1
    @MortezaIpo: What in heavens name does that gist have to do with what the OP is asking about? Commented May 23, 2014 at 9:45
  • @MartijnPieters as I said hope that be useful. Commented May 23, 2014 at 9:47
  • @MortezaIpo: sure, but it isn't. Not in any way that I can see. Perhaps you meant to link to a different gist (that link is over a year old), but in general a link to a gist without explanation isn't much help to begin with. Commented May 23, 2014 at 9:49
  • @MartijnPieters I see. you are right. it just has a simple description. Commented May 23, 2014 at 10:02

1 Answer 1

1

You don't have to give f.readline() an argument at all:

test1 = f.readline()
test2 = f.readline()
test3 = f.readline()

otherwise you limit the number of characters read. f.readline(1) does not mean 'read line 1'; instead you say: 'read a line, but no more than 1 character should be read'.

Quoting from the IOBase.readline() docs:

Read and return one line from the stream. If size is specified, at most size bytes will be read.

Emphasis mine.

Sign up to request clarification or add additional context in comments.

6 Comments

So simple, so elegant, so much noobiness on my part. Thanks for the explanation, i appreciate it!
Okay, heres my problem now. It can print the item happily, but when i recall the variable its giving me things like "10\n". So i did a bit of research and i've been trying to use rstrip like the following, to strip out the \n when i call the variable later, however it ends up giving me a variable such as v1 = ''. Not sure how to embed code into this so ill put it on paste bin at: Link @Martijn Pieters
@user2809413: yes, the newline is included. You can strip that off; test1.rstrip('\n') would remove any newlines from the end of the string, for example (returning the altered string).
Sorry, not really sure how to implement that? Where does the test1 come from?
@user2809413: You used test1 as a variable in your question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.