Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python not recognizing new created files

Tags:

python

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?

like image 787
ifreak Avatar asked Apr 17 '26 23:04

ifreak


2 Answers

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!')
like image 146
Zaur Nasibov Avatar answered Apr 20 '26 13:04

Zaur Nasibov


Do a f.close() and then open it again as text_file = open("test.txt", "r")

like image 38
Ranjith Ramachandra Avatar answered Apr 20 '26 13:04

Ranjith Ramachandra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!