File Write/delete in Python

Writing in File

write() function are used to write in the file.
w mode(write mode) are used to overwrite in the file means it clear all the content which is already written in the file and the write.

Syntax of write() function with 'w' mode

variable_name=open("file_name","a")
variable_name.write(#contents)

Example 1

Soppose in file 'sc.py' we have a program to add two number.

txt='SmallCode is a Educational Website'
file_var1=open("sc.py","w")
file_var1.write(txt)
file_var1.close()
file_var2=open("sc.py","r")
print(file_var2.read())

Output

SmallCode is a Educational Website

Note

If you open the file with any variable then you don't able do read write with one variable you need to openagain with another variable.

Soppose we have a file 'sc.py'.

file_var=open("sc.py","r")
print(file_var.write("SmallCode is a Educational website."))
print(f.read())

Output

print(file_var.write("SmallCode is a Educational website."))
io.UnsupportedOperation: not writable

Syntax of write() function with 'a' mode

 variable_name=open("file_name","a")
 variable_name.write(#contents)

Example 1

Soppose in file 'sc.py' we have a program to add two number.

txt='SmallCode is a Educational Website'
file_var1=open("sc.py","a")
file_var1.write(txt)
file_var1.close()
file_var2=open("sc.py","r")
print(file_var2.read())

Output

a=10
b=20
print("sum:",a+b)
SmallCode is a Educational Website

File Deleting in Python

remove() function of os Module are used to remove the file.

Syntax

import os 
os.remove("file_name")

Example

import os 
os.remove("sc.py")

Here sc.py file is deleted.