4

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

4
  • The tutorial <a href="docs.python.org/tutorial/… this</a>. Commented Mar 22, 2010 at 9:51
  • Any reason, why you want to re-read it again after fetching? (Like, you want to append new data and read the whole file...) Commented Mar 22, 2010 at 9:54
  • @Boldewyn: Presumably to send it back out again at a later time. Appending doesn't require reading what's already in the file. Commented Mar 22, 2010 at 10:00
  • Hello everybody, please my English is not so good. I want to write the text (which I get from AJAX) to a file,i found this example in Ineternet ,and it is interressant ,but i don't no how i can test that.Please can u tell me witch Labrary i want bevor it works ? or can u give me some example how i can do that ,i will very happy. I thank U in advance Denis Commented Feb 4, 2011 at 1:01

4 Answers 4

12

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()
Sign up to request clarification or add additional context in comments.

Comments

6

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()

1 Comment

python doesn't terminate in semi-colons.
5
f = open( 'filename.txt', 'w+' )
f.write( 'text' )
f.close()

f = open( 'filename.txt', 'r' )
for line in f:
    print( line )
f.close()

Comments

2

You can try this out

with open("file.txt", "r+") as file:

     for i in file:
         file.write(i + "\n")
file.close

1 Comment

you don't need close if you're using with

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.