How to read and write a file using python?

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

+3
source share
4 answers

The following code is for reading contents from a file

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

If you want to read using a single line readline (). If you want to read all the lines in a file, readlines () are also used.

The following code to write content to a file

 handle1=open('file.txt','r+') handle1.write("I AM NEW FILE") handle1.close() 
+4
source

If you can use this in a Django view ... try something 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() 
+8
source
 f = open( 'filename.txt', 'w+' ) f.write( 'text' ) f.close() f = open( 'filename.txt', 'r' ) for line in f: print( line ) f.close() 
+4
source

you bad bruh just be better even given better

0
source

All Articles