SaiKiran
SaiKiran

Reputation: 6504

AttributeError: 'module' object has no attribute 'file'

Iam working on a project where we need to find the number of words and also find no of occurences of a particular word.

Testing.py

import unittest
import sys
import string
import funs
from funs import *


empty_list =[]
count = 0
file_name = sys.argv[1]
search = sys.argv[2]
with open(file_name,'r') as f:
     for line in f:
         for word in line.split():
             #Effective Way
            word = word.translate(None, string.punctuation)
            word = word.lower();
            empty_list.append(word)
            count += 1


class TestMyFunction(object):
    def test_search(self):
        self.assertTrue(search_word_fun(empty_list,'kiran'),0)

if __name__ == '__main__':
    unittest.main(exit=False)

funs.py

def longest_word_fun(empty_list,longest_word):
    for each_word in empty_list:
        if (len(each_word) == len(longest_word)):
            print each_word
def search_word_fun(empty_list,search):
    print "No of times %s occurs is %d"%(search,empty_list.count(search))

def count_word_fun(count):  
    print "No of words in file is %d"%(count)

Error Log :

python testing.py file.txt he
Traceback (most recent call last):
  File "testing.py", line 27, in <module>
    unittest.main()
  File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__
    self.parseArgs(argv)
  File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs
    self.createTests()
  File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests
    self.module)
  File "/usr/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'file'

Here I am taking the testing file and while executing the arguments as one as normal text file and other argument is the search keyword.So it need to Test whether it is working or not by unittest.

While executing the function the error came.

Upvotes: 0

Views: 2571

Answers (1)

gntoni
gntoni

Reputation: 487

There is a conflict caused by unittest trying to read the command line arguments you use. You can solve it by reading the arguments and then deleting them before calling unittest.main():

if __name__ == '__main__':
    cmd_parameters = sys.argv[1]
    del sys.argv[1:]
    unittest.main()

Upvotes: 2

Related Questions