将项目放入数组

时间:2018-11-20 07:13:27

标签: python arrays python-3.x

我正在Visual Studio中处理Python项目。我想处理更长的文本文件,这是简化版本:

David Tubb
Eduardo Cordero
Sumeeth Chandrashekar

因此,我使用以下代码来读取此文件:

with open("data.txt", "r") as f:
    f_contents = f.read()
    print(f_contents)

我想将这些项目放到一个看起来像这样的新数组中:

['David Tubb','Eduardo Cordero','Sumeeth Chandrashekar']

有可能吗?

3 个答案:

答案 0 :(得分:3)

是的,以下代码将对此起作用:

output = [] # the output list
nameFile = open('data.txt', 'r') 

for name in nameFile:
    # get rid of new line character and add it to your list
    output.append(name.rstrip('\n'))

print output

# don't forget to close the file!
nameFile.close()

答案 1 :(得分:1)

result = []
with open("data.txt", "r") as f:
    result = f.read().splitlines()
print(result)

输出:

['David Tubb', 'Eduardo Cordero', 'Sumeeth Chandrashekar']

答案 2 :(得分:0)

python声明的打开文件上下文的方法使用的是“ with open”,这可以确保上下文在清理过程中结束。

python.org-pep-0343

dalist = list()
with open('data.txt', 'r') as infile:
    for line in infile.readlines():
        dalist.append(line)

用于顶点处理的其他资源:https://docs.python.org/3/library/contextlib.html