How To Read & Write .txt File In Python?
To Read a File In Python We Just need A simple Code To read Any Text File
For Example :
1-We Need A Text File Whose Path Is = (D:\\a1\\justtest.txt)
2-We Take A variable Suppose I Take 'a' as a variable Note: (You Can Take Any Variable)
3-Then We Take A Open Function
The open() function opens a file, and returns it as a file object
4-After that We Write The Path In Strings and use of double backslash
5-After That We Take r To read the File
'r' is used to read the file
6-Then print the variable.read()
.read is use for read the file
code:
a = open("D:\\a1\\justtest.txt","r")
print(a.read())
Write A File✍:
To Write a File In Python We Just need A simple Code To write Any Text File
For Example :
1-We Need A Text File Whose Path Is = (D:\\a1\\diary.txt)
2-We Take A variable Suppose I Take 'z' as a variable Note: (You Can Take Any Variable)
3-Then We Take A Open Function
The open() function opens a file, and returns it as a file object
4-After that We Write The Path In Strings and use of double backslash
5-After That We Take w To write in the File
'w' is used to write in the file
6-Then print the variable.write()
.write is use to write something in the file
code:
z = open("D:\\a1\\diary.txt","w") z.write("welcome to new file")