Can I hook a "file" to a python script?

dmbkiwi dmbkiwi at yahoo.com
Sat Nov 8 00:56:46 EST 2003


On Fri, 07 Nov 2003 20:39:49 -0800, Scott Chapman wrote:

> Hi!
> 
> I'd like a "file" on the Linux box to actually be the input and output 
> of a Python script.  Anything written to the file would be sent to a 
> database and anything read from the file would come from the database.  
> I know how to do the database end of this but I'm not sure if a script 
> can be hooked to a "file" transparently.  The script would probably 
> have to be run as a daemon.  I doubt there's enough magic in the Linux 
> world to make it so that a read/write would actually launch the script. 
> That'd be Ok.
> 
> Scott

I may be missing the point here, so forgive me if I am.

However, files can be opened as objects and read and written to very
simply in python.

To open a file:

file_object = open('/path/to/file', 'r')

Then you can read it like thus:

file_contents = file_object.read()

or get each line in a list like this:

file_line_list = file_object.readlines()

you can also write to a file.  You have to create the file object first:

save_file = open('filename', 'w')

then you can write to it like:

print >> save_file, 'some text'

you should also close the file objects you open once you're done with them.

Gook luck

Matt




More information about the Python-list mailing list