Nearby lessons

81 of 108

Python - Delete Files

Detailed Tutorial Notes

Q. Program to print the number of lines,words and characters present in the

given file?

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
D:\Python_classes>py test.py
Enter File Name: durga.txt
File does not exist: durga.txt

23)

24) D:\Python_classes>py test.py
25) Enter File Name: abc.txt
26) File exists: abc.txt
27) The number of Lines: 6
28) The number of Words: 24
29) The number of Characters: 149

abc.txt:

All Students are GEMS!!!

All Students are GEMS!!!

All Students are GEMS!!!

All Students are GEMS!!!

All Students are GEMS!!!

All Students are GEMS!!!

Handling Binary Data:

It is very common requirement to read or write binary data like images,video files,audio

files etc.

Q. Program to read image file and write to a new image file?

1) f1=open("rossum.jpg","rb")
2) f2=open("newpic.jpg","wb")
3) bytes=f1.read()
4) f2.write(bytes)
5) print("New Image is available with the name: newpic.jpg")

Handling csv files:

CSV==>Comma seperated values

As the part of programming,it is very common requirement to write and read data wrt csv

files. Python provides csv module to handle csv files.

Writing data to csv file:

1) import csv
2) with open("emp.csv","w",newline='') as f:
3) w=csv.writer(f) # returns csv writer object
4) w.writerow(["ENO","ENAME","ESAL","EADDR"])
5) n=int(input("Enter Number of Employees:"))
6) for i in range(n):
7) eno=input("Enter Employee No:")
8) ename=input("Enter Employee Name:")
9) esal=input("Enter Employee Salary:")
10) eaddr=input("Enter Employee Address:")
11) w.writerow([eno,ename,esal,eaddr])
12) print("Total Employees data written to csv file successfully")

Note: Observe the difference with newline attribute and without

with open("emp.csv","w",newline='') as f:

with open("emp.csv","w") as f:

Note: If we are not using newline attribute then in the csv file blank lines will be included

between data. To prevent these blank lines, newline attribute is required in Python-3,but

in Python-2 just we can specify mode as 'wb' and we are not required to use newline

attribute.

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!Python - OOP Introduction