This document discusses file handling in Python through 4 code examples. The first example demonstrates opening and writing to a file. The second example opens a file in write and binary mode and displays file details. The third example writes encoded data to a file and then reads it back. The fourth example writes 3 lines to a file and confirms the write was successful.
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
138 views
File Handling in Python
This document discusses file handling in Python through 4 code examples. The first example demonstrates opening and writing to a file. The second example opens a file in write and binary mode and displays file details. The third example writes encoded data to a file and then reads it back. The fourth example writes 3 lines to a file and confirms the write was successful.
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1
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