我似乎想不出如何使用文本文件中给出的值并将它们导入到python中来创建列表。我在这里尝试完成的是创建一个游戏板,然后将数字放在上面作为样例集。我必须使用Quickdraw来完成这一点-我知道如何在Quickdraw上获得数字,但我似乎不能从文本文件中导入数字。以前的分配涉及让用户输入值或使用I/O重定向,这有点不同。有人能在这方面帮我吗?
发布于 2012-11-22 06:31:22
取决于要在要获取的列表中读取和输出的文件的内容。
# assuming you have values each on separate line
values = []
for line in open('path-to-the-file'):
values.append(line)
# might want to implement stripping newlines and such in here
# by using line.strip() or .rstrip()
# or perhaps more than one value in a line, with some separator
values = []
for line in open('path-to-the-file'):
# e.g. ':' as a separator
separator = ':'
line = line.split(separator)
for value in line:
values.append(value)
# or all in one line with separators
values = open('path-to-the-file').read().split(separator)
# might want to use .strip() on this one too, before split method如果我们知道输入和输出需求,它可能会更准确。
发布于 2012-11-22 04:40:45
这里有两个步骤:
此页面可能会对您有所帮助:http://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
https://stackoverflow.com/questions/13501573
复制相似问题