2015-03-25 101 views
0

我试图设计一个函数,它基本上将一个文件变量作为参数,并返回一个包含具有文件中最早的帐户日期的客户的数据的列表。Python搜索文件的最早日期

假设这是该文件(txt文件)的内容:

12345,Tom,Black,300.00,1998-01-30 
23456,Alice,Smith,1200.50,1998-02-20 
14567,Jane,White,900.00,1998-07-01 
43564,Weilin,Zhao,450.25,1998-01-03 
45432,Bina,Mehta,278.95,1998-03-21 

我的代码是:

l = open(r'C:\Users\John\Downloads\customers.txt','r', encoding="utf-8") 

contents= l.readlines() 

def get_earliest_customer(contents): 

    with open(r'C:\Users\John\Downloads\customers.txt','r', encoding="utf-8") as f: 
     print(min(f, key=(lambda l: string(l.strip().split(",")[4])))) 

l.close() 

get_earliest_customer(contents) 

这些课程给我的erorr:

print(min(f, key=(lambda l: string(l.strip().split(",")[4])))) 
    File "C:\Users\John\Home\HPcomputers\src\4.py", line 10, in <lambda> 
    print(min(f, key=(lambda l: str(l.strip().split(",")[4])))) 
NameError: name 'string' is not defined 

建议/意见,以解决这个问题表示赞赏,我指出了我想要搜索的点[4]是导致每条线上的日期都位于那里。

+0

你打算与调用'字符串()'完成什么? 'split()'的结果已经是一个字符串列表。 – Dolda2000 2015-03-25 04:30:07

+2

python中没有'string'。 'str'就是你想要的。 – justanothercoder 2015-03-25 04:30:31

+0

@justanothercoder好headup – Giovanni 2015-03-25 04:33:35

回答

1
l = open(r'C:\Users\John\Downloads\customers.txt','r', encoding="utf-8") 

contents= l.readlines() 

def get_earliest_customer(contents): 

    with open(r'C:\Users\John\Downloads\customers.txt','r', encoding="utf-8") as f: 
     print(min(f, key=(lambda l: str(l.strip().split(",")[4])))) 

l.close() 

get_earliest_customer(contents) 

给输出:

43564,Weilin,Zhao,450.25,1998-01-03 

这是我想要的东西,从而从字符串的变化为str,虽然小的变化提供我想要的输出。

1

试试这个:

file1 = open('data.txt', 'r') 

print min([line for line in file1.read().splitlines()], key=lambda x: x.rsplit(',', 1)[1]) 

输出:

43564,Weilin,Zhao,450.25,1998-01-03 
1

一个更好的办法来做到这一点是将日期字符串转换为日期对象,然后做比较。

我也不知道你为什么要读两次文件,即使你将它传递给你的函数,也不会使用contents变量。

import datetime 
import csv 

fmt = '%Y-%m-%d' 

def get_earliest_customer(filename): 
    contents = [] 
    with open(filename) as f: 
     reader = csv.reader(contents, delimiter=',') 
     for row in reader: 
      contents = row[:-1]+[datetime.datetime.strptime(row[-1], fmt)] 

    return min(contents, key=lambda x: x[-1]) 

print(get_earliest_customer(r'C:\Users\John\Downloads\customers.txt'))