How to read and write a file using python?


Question

I want to write the text (which I get from AJAX) to a file, and then read it.

1
3
3/22/2010 9:50:48 AM

Accepted Answer

The following code for read the content from a file

handle=open('file','r+')
var=handle.read()
print var

If you want to read a single line use the readline(). If you want to read the whole lines in the file use the readlines() also

The following code for writing the content to the file

handle1=open('file.txt','r+')
handle1.write("I AM NEW FILE")
handle1.close()
4
1/12/2014 11:19:40 AM

If you can use this in Django view... try somethink like this:

def some_view(request):
    text = request.POST.get("text", None)
    if text is not None:
        f = open( 'some_file.txt', 'w+')
        f.write(text)
        f.close()
    return HttpResponse()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon