简体   繁体   English

读取数据文件并从对象中列出清单

[英]Reading a file of data and making a list from the objects

I have some data in a separate file that is like this: 我在一个单独的文件中有一些数据,如下所示:

bob 11 20
sam 30 19
jay 50 10

and so on... I am trying to : 依此类推...我正在尝试:

  1. Open the file. 打开文件。
  2. Read each line. 阅读每一行。
  3. Make an object with the data from that line. 使用该行中的数据作为对象。

I'm going about it like this : 我正在这样做:

with open("data.txt") as f:
    for lines in f:
        f.readlines()
data = lines.split()

Is this the correct way to make sure each line is kept in it's own list? 这是确保每一行都保存在自己的列表中的正确方法吗? Like for example [bob, 11, 20] ? 例如[bob,11,20]?

You can iterate over the file generator in a list comprehension and split each line into lists of items: 您可以在列表理解中遍历文件生成器,并将每一行拆分为项目列表:

with open("data.txt") as f:
    data = [line.split() for line in f]

No this will give you only the last line, you should instead do it like this: 不,这只会给您最后一行,而应该这样:

data = []
with open("data.txt") as f:
    for line in f:
        data.append(line.split())

This code will help you: 此代码将帮助您:

data = []
lines = [line.rstrip('\n') for line in open('data.txt')]
for line in lines:
   data.append({'name' : line.split()[0], 'something1' : line.split()[1], 'something2' : line.split()[2]})

you can loop or even get data info very easy 您可以非常轻松地循环甚至获取数据信息

Just from dealing with lots of lists today, I can offer another solution: to get each line as a list and make a list of those lists, eg [['bob 11 20'], ['sam 30 19'], ['jay 50 10']] I used this function: 从今天处理大量列表开始,我可以提供另一种解决方案:将每一行作为列表并列出这些列表,例如[['bob 11 20'], ['sam 30 19'], ['jay 50 10']]我使用了此功能:

def read(): reader = csv.reader(open("list.txt"), delimiter="\\t") list = [r for r in reader] print(list)

There are a lot of ways to deal with lists and the one that works for your project is the 'correct' way. 处理列表的方法有很多,而对您的项目有效的方法是“正确”的方法。 Earlier today I was teasing apart sqlalchemy queries into dictionaries and converting those into strings and piping those out to datetime formatting, them appending them all back together! 今天早些时候,我将sqlalchemy查询分解为字典,然后将其转换为字符串,然后将它们以日期时间格式输出,将它们全部附加在一起! You can preserve the lines individually if thats what you need, or by iterating over them again with a function, pull out more granular data for your project. 您可以根据需要单独保存行,或者通过使用函数再次对其进行遍历,从而为项目提取更多的细粒度数据。 Good luck! 祝好运!

I have defined a Person class (as an example for an object) that is created using each line of the file 我已经定义了使用文件的每一行创建的Person类(作为对象的示例)

class Person:
    def __init__(self, name, age, weight):
        self.name = name
        self.age = age
        self.weight = weight

    def __str__(self):
        return 'name:{},age:{},weight:{}'.format(self.name, self.age, self.weight)


persons = []
with open('data.csv', 'r') as f:
    lines = f.readlines()
    for line in lines:
        fields = line.split(' ')
        persons.append(Person(fields[0], fields[1], fields[2]))
for person in persons:
    print(person)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM