Reputation: 2595
Ok, I am trying to simply learn reading and writing text files in python. I can read the file etc but I get unexpected results when I attempt to write the file using write("my string")
and then go to execute my code the file gets wrote to but the first line that was wrote will not fully print out. This happens in Vim with pymode and from the command line as well as interpreter. Here is the code:
#!/usr/bin/python
f = open('/Users/Desktop/data.txt', 'r+')
f.write("Test")
for lines in f:
print lines
f.close()
Now when I execute this file to write to data.txt
the output will look like this:
est <------ the "T" in Test is totally cut off. I hope this makes sense, Thanks in advance.
Upvotes: 0
Views: 527
Reputation: 5993
I think your problem here is that you write to a file object and then immediately read back from it.
Try adding the line
f.seek(0)
after you write to the file but before you read from it. This repositions where in the file Python is looking to the beginning.
Upvotes: 3