Python初学者。 我有一个函数,它应该打开两个文件,在空格处拆分它们,并将它们存储在列表中,以便在另一个函数中访问。 我的第一个功能是:
listinput1 = input("Enter the name of the first file that you want to open: ")
listinput2 = input("Enter the name of the first file that you want to open: ")
list1 = open(listinput1)
list1 = list(list1)
list2 = open(listinput2)
list2 = list(list2)
metrics = plag(list1, list2)
print(metrics)
但是当我执行第二个函数时,我看到列表并没有像我预期的那样在空格处拆分。我尝试了split函数,还尝试了使用for循环来迭代列表的每个增量。你知道吗
一些建议:
当你
open()
一个文件时,你也需要close()
它。您没有这样做(一般来说,单独做是个坏主意,因为如果程序首先遇到异常,可能会错过结束)。你知道吗这里首选的Python习惯用法是
with open(path) as f
:调用
open(listinput1)
时,会得到一个file对象。对此调用list()
将获得文件中的行列表,例如:要从文件中获取包含文本的字符串,请对对象调用
read()
方法,然后对该字符串使用split()
方法。你知道吗你要了两次第一份文件。第二个字符串是否应该是“输入要打开的第二个文件的名称”?
以下是代码的更新版本,其中包含这些更改:
相关问题 更多 >
编程相关推荐