[英]Importing a text file to create a list in Python 3.x?
我似乎無法弄清楚如何使用文本文件中給定的值並將其導入python以創建列表。 我要在這里完成的工作是創建一個游戲板,然后在其上放一些數字作為樣本集。 我必須使用Quickdraw來完成此操作-我有點知道如何在Quickdraw上獲取數字,但似乎無法從文本文件中導入數字。 先前的分配涉及使用戶輸入值或使用I / O重定向,這有點不同。 有人可以幫我嗎?
取決於要讀取的文件的內容,並在要獲取的列表中輸出。
# 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
如果我們知道輸入和輸出要求,可能會更准確。
這里有兩個步驟:
打開文件
閱讀台詞
該頁面可能會幫助您: http : //docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.