File Handling In Python-
Ex-
class Test: file = None def main(): try: Test.file = open("./test.txt") #builin module(We are assuming that you have test.txt in same folder) print("****Read the content at an instance****") content = Test.file.read() print(content) print("****Read the content char by char****") for ch in content: print(ch, end='') except Exception as ex: print("Exception occurred-", ex) finally: if Test.file is not None: Test.file.close() print("\n*****File Closed******") Test.main() Output- ****Read the content at an instance**** Hi Welcome Bye ****Read the content char by char**** Hi Welcome Bye *****File Closed******
Open Function Is Having 3 Modes-
1) “R” –
- 1) Open the file in read mode.
- 2) If file is present – It will open the file and will return the pointer.
- 3) If file is not present – It will raise the exception.
2) “W” –
- 1) Open the file into the write mode.
- 2) If file is present – It open the file and remove all the existing content.
- 3) If file is not present – It will create a new file.
3) “A” –
- 1) Open the file into the append mode.
- 2) If file is present – It open the file and place the cursor at the end of the file to add new content.
- 3) If file is not present – It will create the new file.
Ex-
class Test: src = None dest = None def main(): try: Test.src = open("./test1.txt", "r") Test.dest = open("./test1.py", "w") for ch in Test.src: Test.dest.write(ch) print("Data Copied") finally: if Test.src is not None: Test.src.close() if Test.dest != None: Test.dest.close() Test.main() Output- Data Copied
-
-
Qsn-
How to read the content of CSV(comma separated values) file?
-
Ans-
import csv #predefined module file = open("./Test.csv", "r") print("CSV File Opened") table = csv.reader(file) for record in table: print(record) file.close() print("File Closed")
-
-
Qsn-
How to read the content of XLS file?
-
Ans-
import xlrd wb = xlrd.open_workbook("Demo1.xlsx") sheet = wb.sheet_by_index(1) for i in range(sheet.nrows): #sheet.nrows - Total no of rows for j in range(sheet.ncols) :#sheet.ncols - Total no of colomns print(sheet.cell_value(i,j), end=' ') print() Output- Name Age A2 171.0 B2 898.0 C2 787.0