In: Computer Science
What method is used to set up a file for reading and/or writing?
code in python
Here is the Code:-
This is the default syntax to set up a file for reading / writing:-
f=open(filename,mode)
Note:- filename is the location for the file and mode represents the operations you are going to use after opening file
We have many modes like read, append, write etc... Then the python code for each operation is as follows below:-
f=open("sample.txt","r")
This mode r means Opening file for reading. if the file is not present eroor will come.
f=open("sample.txt","r+")
This mode r+ means opening file for reading and writing purpose if the file is not present eroor will come.
f=open("sample.txt","w")
This mode w means Opening file for writing purpose only if the file is not present it will create one if file has contents it will overwrite the content.
f=open("sample.txt","w+")
This mode w+ means Opening file for writing and reading purpose and if the file is not present it will create one if file has contents it will overwrite the content
f=open("sample.txt","a")
This mode a means Opening file for writing purpose and if the file is not present in the location it will create one and if file has contents it will append the content
f=open("sample.txt","a+")
This mode a+ means Opening file for writing and reading purpose and if the file is not present in the location it will create one and if file has contents it will append the content
Note:-
Never forgot to close the file. If the file is not closed
properly it may cause data loss or some odd behaviour. Using
"with" keyword while opening file it will close
the file after completion of the program
Indentation:-
***If you have any doubt please feel free to comment...Thank you...Please UPVOTE***