Python:从文件创建元组列表

时间:2014-04-18 15:45:30

标签: python-3.x

我有一个测试文件,我想使用文件上的数据加载创建元组列表。该文件的数据如下>如何成功加载文件然后创建元组。

ocean,4
-500, -360
-500, 360
500, 360
500,-360

2 个答案:

答案 0 :(得分:0)

一种非常直接的方法是使用csv模块。 E.g:

import csv

filename = "input.csv"

with open(filename, 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        print(row)

答案 1 :(得分:0)

使用csv模块解析文件:

import csv

output = []
with open('input_file') as in_file:
    csv_reader = csv.reader(in_file)
    for row in csv_reader:
        output.append(tuple(row))

print output

这将返回一个元组列表,每个元组对应于输入文件中的每一行。

[('ocean', '4'), ('-500', ' -360'), ('-500', ' 360'), ('500', ' 360'), ('500', '-360')]
相关问题