【发布时间】:2022-01-08 19:05:13
【问题描述】:
我是python新手,我写了一个python程序,它读取文件列表并将特定字符(ch)的总数保存在一个字典,然后返回它。
程序运行良好,现在我正在尝试编写一个简单的测试代码来测试程序。
我尝试了以下代码,
def test_read_files():
assert read_files("H:\\SomeTextFiles\\zero-k.txt", 'k') == 0, "Should be 0"
if __name__ == "__main__":
test_read_files()
print("Everything passed")
我将程序命名为 test_read_files.py
我的python代码如下:
# This function reads a list of files and saves number of
# a particular character (ch) in dictionary and returns it.
def read_files(filePaths, ch):
# dictionary for saing no of character's in each file
dictionary = {}
for filePath in filePaths:
try:
# using "with statement" with open() function
with open(filePath, "r") as file_object:
# read file content
fileContent = file_object.read()
dictionary[filePath] = fileContent.count(ch)
except Exception:
# handling exception
print('An Error with opening the file '+filePath)
dictionary[filePath] = -1
return dictionary
fileLists = ["H:\\SomeTextFiles\\16.txt", "H:\\SomeTextFiles\\Statement1.txt",
"H:\\SomeTextFiles\\zero-k.txt", "H:\\SomeTextFiles"]
print(read_files(fileLists, 'k'))
我将其命名为 read_files.py
当我运行测试代码时,出现错误:NameError: name 'read_files' is not defined
程序和测试代码都在同一个文件夹中(虽然不同于python文件夹)。
【问题讨论】:
标签: python-3.x file testing