我有用于在另一个列表中打印嵌套列表的模块:
import sys
def custom_print(the_list, indent=False, level=0, fh=sys.stdout):
for each_item in the_list:
if isinstance(each_item, list):
custom_print(each_item, indent, level+1, fh)
else:
if indent:
for tab_stop in range(level):
print("\t", end="", file=fh)
print(each_item, file=fh)
我尝试在一个程序中导入此模块,该程序用于将文本文件打印到两个单独的列表中。然后我想把这些列表写到我硬盘上的两个文件中。
import listsprint
man = []
other = []
try:
data = open("speech.txt")
for each_line in data:
try:
(role, line_spoken) = each_line.split(":", 1)
line_spoken = line_spoken.strip()
if role == "Man":
man.append(line_spoken)
elif role == "Other Man":
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print("The data file is missing")
try:
with open("man_data.txt", "w") as man_file:
listsprint.custom_print(man, file=man_file)
with open("other_data.txt", "w") as other_file:
listsprint.custom_print(other, file=other_file)
except IOError as err:
print("File error: " + str(err))
但是当我运行程序时,会发生异常。
Traceback (most recent call last):
File "C:\....\....\Desktop\drills\chapter3\speech.py", line 26, in <module>
listsprint.custom_print(man, file=man_file)
TypeError: custom_print() got an unexpected keyword argument 'file'
答案 0 :(得分:2)
与错误一样,您的custom_print
函数不接受file
参数。您是否意味着使用fh
代替?