Home > Enterprise >  Count and store in a file
Count and store in a file

Time:06-13

counts the occurrences of letter a in the first 200 characters in the file characters.txt the result should get stored inside a new folder with a txt file

Example: characters.txt: abcdefghijklmnopqerstuvwxzy

so there is 1 occurrence of g

then "1" should be stored in foulder/file.txt

  file = open(filename, "r")
  text = file.read()
  count = 0
  for char in text:
    if char == letter:
        count  = 1

os.mkdir("g")
f = open("res.txt", mode = "w")
f.write(count)
f.close

CodePudding user response:

Your code works, but in the samples provided you dont call it.

I made a local version without your file code.

def letterFrequency(letter):
    count = 0
    for char in 'abcdefghijklmnopqerstuvwxzy':
        if char == letter:
            count  = 1
    return count
print(letterFrequency('g'))

If you only want to search the first 200 character of a file you should use a while loop. Also you will need to account for rows with less than 200 characters.

CodePudding user response:

I modified your given example and added some improvements. The code below is a minimal working example:

import os

file = open("./Desktop/text.txt", "r")
text = file.read()
count = 0
letter = "g"
if len(text) < 200:
    text = text[0:199]
for char in text:
    if char == letter:
        count  = 1

        

try:       
    os.mkdir("./Desktop/DIR")
except FileExistsError:
    print("Dir already exists")
f = open("./Desktop/DIR/res.txt", "w")
f.write(str(count))
  • Related