-
Notifications
You must be signed in to change notification settings - Fork 2
/
Lawerene_Woods_A6.py
122 lines (87 loc) · 2.19 KB
/
Lawerene_Woods_A6.py
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
'''
Lawrence Woods
Assigement # 6 Working with Data Bases
3/19/2018
'''
def replaceText(filename, word):
linetext = ""
inputFile = open(filename)
for line in inputFile:
linetext += line.replace(word, "")
inputFile.close()
# print(linetext)
outfile = open(filename, "w+")
outfile.write(linetext)
outfile.flush()
outfile.close
# inputFile = open(filename, "w+")
# inputFile.write(linetext)
# inputFile.close()
def main():
filename = input("Enter file name: ")
if os.path.exists(filename):
word = input("Enter word to replace: ")
replaceText(filename, word)
else:
print("File doesn't exist")
main() # to call main() method
2) count
all
occurences
of
words, characters and lines
import os.path
def countOccurences(filename):
lines = 0
words = 0
chars = 0
with open(filename, 'r') as fileToRead:
for line in fileToRead:
wordsInLine = line.split()
lines += 1
words += len(wordsInLine)
chars += len(line)
print("%s characters" % (chars))
print("%s words" % (words))
print("%s lines" % (lines))
def main():
filename = input("Enter file name: ")
if os.path.exists(filename):
countOccurences(filename)
else:
print("File doesn't exist")
main()
3) create
random
integers
import os.path
import random
def writeRandomNumbers(filename):
numbers = ""
randNumber = []
sortedNumber = ""
with open(filename, 'w+') as fileToWrite:
for num in range(1, 101):
numbers = numbers + " " + str(random.randint(1, 100))
# print(numbers)
fileToWrite.write(numbers)
fileToWrite.flush()
fileToWrite.close()
with open(filename, "r") as fileToRead:
for line in fileToRead:
# print(line.split(" "))
randNumber = [int(x) for x in line.split(" ") if len(x) > 0]
# print(randNumber)
with open(filename, 'w+') as fileToWrite:
for elem in sorted(randNumber, key=int):
sortedNumber = sortedNumber + " " + str(elem)
fileToWrite.write(sortedNumber)
fileToWrite.flush()
fileToWrite.close()
def main():
filename = input("Enter file name: ")
if os.path.exists(filename):
print("The file already exist")
else:
writeRandomNumbers(filename)
main()