-3

I got nothing back from the command readline(). I am new to python and totally confused now.

my_file = open("test.txt", "w+") my_file.write("This is a test") print my_file.readline() 
4
  • we'll need a bit more of your code in order to understand the problem you're having Commented Aug 1, 2016 at 16:46
  • 5
    In order to read the line you'd have to open the file in read mode. Commented Aug 1, 2016 at 16:47
  • 6
    Don't post images of code. They're harder to read, copy and search for. Commented Aug 1, 2016 at 16:47
  • 1
    you need my_file.seek(0) Commented Aug 1, 2016 at 16:51

2 Answers 2

5

When you write to a file, you overwrite any previous contents of the file and leave the pointer at the end of the file. Any attempt to read after that will fail, since you're already at the end of the file.

To reset to the beginning of the file and read what you just wrote, use:

my_file.seek(0) 
Sign up to request clarification or add additional context in comments.

Comments

0

Because after you wrote content in you file. the cursor is at the end of the file. Before you use readline(), use my_file.seek(0) first, If your file content is only This is a test, you can get your want. Deep into this, please go to : https://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-files

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.