-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest5.py
More file actions
60 lines (52 loc) · 1.94 KB
/
test5.py
File metadata and controls
60 lines (52 loc) · 1.94 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
# This file contains sample code for various Python concepts such as file handling, string manipulation, and functions.
# Code to create a file and write some content into it
f = open("practise.txt", "w")
f.write("This is a practise file.\n")
f.write("Hi Everyone.\n")
f.write("I am learning Python.\n")
f.write("I am also learning Java.\n")
f.close()
# Code to read the content of the file and check if a word is present in it, then replace a word and write the updated content back to the file
with open("practise.txt", "r") as f:
content = f.read()
print(content)
if content.find("Java") != -1:
print("The word 'Java' is present in the file.")
else:
print("The word 'Java' is not present in the file.")
replacedContent = content.replace("Python", "Java")
print(replacedContent)
with open("practise.txt", "w") as f:
f.write(replacedContent)
f.close()
# Code to find a word in the file and print the line number where it is found
def findWordInFile(filename, word):
with open(filename, "r") as f:
content = f.read()
if content.find(word) != -1:
print("The word '" + word + "' is present in the file.")
else:
print("The word '" + word + "' is not present in the file.")
f.close()
findWordInFile("practise.txt", "Python")
# Code to search for a word in the file and print the line number where it is found
def searchWordInFile():
with open("practise.txt", "r") as f:
found = True
i = 1
while found:
content = f.readline()
if not content:
break
if content.find("learnings") != -1:
print("The word 'Python' is present in the file. Found at line number: ", i)
break
i += 1
f.close()
return -1
print(searchWordInFile())
# Code to read the content of a file and print it
with open("practise.txt", "r") as f:
content = f.read()
print(content)
f.close()