我正在使用日期中的月份搜索csv文件:
Jackson,Samantha,2 Heather Row,Basingstoke,RG21 3SD,01256 135434,23/04/1973,sam.jackson@hotmail.com
Vickers,Jonathan,18 Saville Gardens,Reading,RG3 5FH,01196 678254,04/02/1965,the_man@btinternet.com
Morris,Sally,The Old Lodge, Hook,RG23 5RD,01256 728443,19/02/1975,smorris@fgh.co.uk
Cobbly,Harry,345 The High Street,Guildford,GU2 4KJ,01458 288763,30/03/1960,harry.cobbly@somewhere.org.uk
Khan,Jasmine,36 Hever Avenue,Edenbridge,TN34 4FG,01569 276524,28/02/1980,jas.khan@hotmail.com
Vickers,Harriet,45 Sage Gardens,Brighton,BN3 2FG,01675 662554,04/04/1968,harriet.vickers@btinternet.com
存在以下几个问题:;没有显示所有相关人员,当重试时,它不起作用并产生错误:
1. Surname
2. D.O.B
3. Quit
Please select an option: 2
Please enter the birth month in a two digit format e.g. 02: 12
Month not found.
Please enter the birth month in a two digit format e.g. 02: 02
Month not found.
Please enter the birth month in a two digit format e.g. 02: 02
Month not found.
Please enter the birth month in a two digit format e.g. 02: 03
Month not found.
Please enter the birth month in a two digit format e.g. 02: 12
Month not found.
Please enter the birth month in a two digit format e.g. 02: 01
Month not found.
Please enter the birth month in a two digit format e.g. 02:
Must be a number
Please enter the birth month in a two digit format e.g. 02: 04
Month not found.
Please enter the birth month in a two digit format e.g. 02: 50
Must be 1-12
Please enter the birth month in a two digit format e.g. 02:
这是代码:
def input_month():
addrsBk
while True:
try:
month = int(input("Please enter the birth month in a two digit format e.g. 02: "))
except ValueError:
print("Must be a number")
else:
if month in range(1, 13):
return month
print("Must be 1-12")
def DOB_search(BkRdr):
addrsBk
while True:
search_month = input_month()
addrsBk
for row in BkRdr:
DOB = row[6]
day,month,year = DOB.split("/")
if search_month == int(month):
surname = row[0]
firstname = row[1]
print(firstname, " ",surname)
return"".join((firstname, surname))
addrsBk.close
print("Month not found.")
问题是第一次执行for row in BkRdr:
时,文件已耗尽,指针为EOF(文件结束),没有更多的行可读取。然后,第二次它通过for row in BkRdr:
时,不再执行任何块。
要解决此问题,必须将文件指针指向具有.seek(0)
属性的文件的开头。
如果你打开了这样的csv文件:
myFile = open('file_01.csv', mode='r')
BkRdr = csv.reader(myFile, delimiter=',')
你可以用修复你的代码
for row in BkRdr:
DOB = row[6]
day,month,year = DOB.split("/")
if search_month == int(month):
surname = row[0]
firstname = row[1]
print(firstname, " ",surname)
return"".join((firstname, surname))
addrsBk.close
print("Month not found.")
myFile.seek(0)
<file>.seek(int)
将文件行指针放在int
编号的位置,在本例中放在文件(BOF)的开头。
在任何情况下,这都不是csv文件的问题,而是文件对象的问题。你可以阅读:
文件对象的方法