-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday_13filehandling.py
More file actions
79 lines (53 loc) · 2.18 KB
/
Copy pathday_13filehandling.py
File metadata and controls
79 lines (53 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#-----------------------------------------------------------------------------------------------------------------
#File Handling
#-----------------------------------------------------------------------------------------------------------------
#File_name: data.txt
#contents in file(data.txt)
#Fruits: Apple, Mango, Orange, Banana
#Vegetables: Carrot, Potato, Cabbage, Raddish
#1. Reading Entire file
with open("data.txt", "r") as file:
res = file.read()
print(res)
#-----------------------------------------------------------------------------------------------------------------
#2. Reading the file line by line
file = open("data.txt","r")
info = file.readline()
print(info)
file.close()
#-----------------------------------------------------------------------------------------------------------------
#3. Writing into the file
file = open("data.txt", "r")
nf = file.write("Dairy: Milk, Cheese, Butter, Panner, Curd")
print(nf)
file.close()
#-----------------------------------------------------------------------------------------------------------------
#4. Appending into the file
file = open("data.txt", "a")
af = ("Ice-cream: Vanilla, Chocolate, Strawberry, Blackcurrent")
res = file.write( af + "\n" )
print(res)
print("Sucessfully appended")
#-----------------------------------------------------------------------------------------------------------------
#5.counting lines using readlines()
with open("data.txt", "r") as f:
lines = f.readlines()
count = len(lines)
print("Number of lines in the file:", count)
#------------------------------------------------------------------------------------------------------------------
#6.counting lines using loop
f=open("data.txt", "r")
count=0
for line in f:
count+=1
print("Total lines:", count)
#------------------------------------------------------------------------------------------------------------------
#7.Counting Words in a file
with open("data.txt", "r") as f:
line = f.readlines()
count=0
for line in f:
words = line.split()
count += len(words)
print("Total Words:", count)
#--------------------------------------------------------------------------------------------------------------------