I wrote a plugin in which one of the PHP files itself opens and writes another small text file.
How to grant this PHP file the right permissions?
You will never be able to guarantee this functionality. Filesystem level permissions are ultimately beyond the power of PHP, and thus, WordPress. Though you can try and it may work on some systems/configurations there is no way to guarantee it and nothing you can do if the system will not allow you to change permissions. Why do you think WordPress doesn't just change the permissions on the
.htaccess file rather than issue a warning that the file is not writable by the server?
Saving to the "uploads" directory would be your best bet, but that is most likely going to be an illogical place for your file.
My advise is to refactor the code and use options, or post meta, or something that you can depend up.
If you have control of where the file is going to write to (read: the site is "yours"), you can set the folder of the destination writtable by PHP and forget about the issue. If, however you are planning on making the plugin public, your best bet is to save the data into the database as stated above.