Reputation: 41
I'm relatively new to python and I have written a single python script which does the following:
The problem I face is once the file(a.txt) is written and same is read, the contents are not read.
I use time.sleep()
after the txt file(a.txt) is written and then proceeded with reading the same.
But whats happening is the script is stopping it's execution for the time period mentioned in the sleep method and the txt file is not read.
I need a scenario where the same script must write to a text file and read instantly.
Could someone help me please? Thanks in advance.
Upvotes: 0
Views: 474
Reputation: 43495
If you write to a file, the "current position" is at the end of the file after the write. To read from the same file, you have to use the seek method to go to the start of the file.
foo = open("bla.txt", "w+")
foo.write("your text here")
foo.seek(0)
lines = foo.readlines()
Upvotes: 3
Reputation: 3100
I suspect the approach is not the best in this case.
Why would you ever need to sequentially write and read on exactly the same file?
It looks like you're doing something like
while True:
big_string = generate_big_string()
open(filename, 'w').write(big_string)
big_string = open(filename).read()
if that's the case then just keep the string in memory, there is no point in writing and reading all the time. If it's not the case then you should probably post some code to get better help.
Upvotes: 0
Reputation: 11728
In order to read the file you just wrote it should only be necessary to close the file (thus flushing the buffer), you shouldn't need to block with the sleep method, for example
filepath="myfilepath"
with open(filepath,'w') as f:
f.write("hello")
with open(filepath,'r') as f:
print(f.read())
In this case the "with" keyword automatically calls f.close() on the file when it's block is closed. The "with" keyword does not work in early versions of python. The above is equivalent to doing this explicitly:
filepath="myfilepath"
f = open(filepath,'w')
f.write("hello")
f.close()
f = open(filepath,'r')
print(f.read())
f.close()
The close function flushes the buffer.
Depending of your use case it might be better to use some other type of data structure to store your temporary value like a simple variable. Have fun learning python.
Edit: the "with" statement was introduced in python 2.5
Upvotes: 0