-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()
Erik Godard
  • 5,930
  • 6
  • 30
  • 33
S.Tan
  • 1
  • 1

2 Answers2

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)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
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

Joey.Chang
  • 164
  • 2
  • 14