How to read and write to file using python.

Reading a file using python

Writing to a file using python

open("/path_to_file","Mode_on_file")

We can read a txt, csv, json, binary files using python open function which will take two arguments as input.

We can read compressed gzip files too using gzip.open("file", "mode")

File location : path to file

Type of operation on File:

r - : read only

r+ : read and wite

w : write only

w+ : read and write

a : append

a+ append and read

fileread.close() # will flushes the memory used by file

Source code:

Reading from file:

fileread = open("myfile.txt","r+") print(fileread.read()) # reads whole files to a string print(fileread.readline()) # reads only single line

fileread.close()

We need to use  fileread.seek(n) to move the cursur to nth position in the file.

If we use fileread.seek(0) object indexes to first character of the file.


Writing to file:

filewrite = open("myfile.txt","w")

mystring = 'Hello how are you?'

filewrite.write(mystring)

filewrite.close()




 



Comments