I have a python script that will create a text file and then will run a command on this newly created file.
The problem is that the command line is not recognizing the newly created file and I'm getting an error that the file is empty.
my code is something like this:
randomval is a function that will create random characters and return them as a string.
text_file = open("test.txt", "w")
text_file.write(randomval(20,10))
# do something with the `test.txt` file
but I'm getting an error that the file test.txt is empty.
Is there anyway to solve this?
This happens because unless you flush or close the file, the OS will not write any data to the disk. To make sure that the file is closed, use the with statement:
with open("test.txt", "w") as f:
f.write(randomval(20,10))
print('Whoa, at this point the file descriptor is automatically closed!')
Do a f.close() and then open it again as text_file = open("test.txt", "r")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With