Program-06: File handling in python
#1 Python code to create and write in to a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write(" It allows us to write in a particular file")
print("Successfully writing in to the file is completed")
file.close()
Output: Successfully completed
#2 Open a file in write and binary mode.
fob = open("app.log", "wb")
#Display file name.
print("File name: ", fob.name)
#Display state of the file.
print("File state: ", fob.closed)
#Print the opening mode.
print("Opening mode: ", fob.mode)
Output: File name: app.log
File state: False
Opening mode: wb
#3 Encoding the writing data in to the file
with open('app.log', 'w', encoding = 'utf-8') as f:
#first line
f.write('my first file\n')
#second line
f.write('This file\n')
#third line
f.write('contains three lines\n')
with open('app.log', 'r', encoding = 'utf-8') as f:
content = f.readlines()
for line in content:
print(line)
output: my first file
This file
contains three lines
#4 program for to check either writing in to the file r not
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
Output: Successfully write the three lines in to the files