0

can anyone tell me what is wrong with my code?

def count_letters(in_file, out_file):
    in_file = open("in_file.txt", "r")
    for line in in_file:
        for x in sorted(line):
            count = x.count()
            out_file = open("out_file.txt", "w")
            print(x, " ", count)
    in_file.close()
    out_file.close()

print(out_file)

it's supposed to

  • Takes two filenames (in_file and out_file)as arguments
  • Opens and reads the input file specified by in_file, and counts the number of occurrences of each letter (in a case-insensitive manner)
  • Writes the result in the output file specified by out_file

when I run it, it tells me that "in_file" is not defined, but I have defined it, and made an "in_file.txt."

any help would be appreciated!

2
  • 1
    It might be helpful to see how you're calling the function. Also, you're passing in in_file but then re-defining it inside the function. You might want to reconsider that. Commented Apr 21, 2015 at 2:14
  • You probably want to move out_file = open("out_file.txt", "w") out of the for loops. And you never write to the output file. Commented Apr 21, 2015 at 2:42

2 Answers 2

1

You want pass "in_file.txt" as in_file variable and use it like:

 in_f=open(in_file,"r")

similarly for out_file otherwise, what is the point of making a function?

But i think your error relates of not having "in_file.txt" in your current working directory, you can check with

import os
print os.getcwd()

this will show what files code can see

Sign up to request clarification or add additional context in comments.

2 Comments

I have to make a function because its part of the requirement for this task, I just couldn't figure out why it kept saying "not defined", thanks though
just try changing the name of what you are passing in to the function...i think compiler is getting confused between variable you pass in and local variables...try deleting arguments to the function ..it should work then
0
in_file = open(in_file, "r") # you must do the way so got an error

try this function:

def count_letters(in_file, out_file):

    in_file_fd = open(in_file, "r") # open in file
    out_file_fd = open(out_file, "w") # open out file

    for line in in_file_fd:
        for x in sorted(line):
            count = line.count(x)
            res = x + " " + str(count) + '\n'
            print (res)
            out_file_fd.write(res) # write the data into out file

    in_file_fd.close() # close in_file
    out_file_fd.close() # close out_file

count_letters('test.py', 'out_file')

It works for me, hope helpful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.