这是我的代码:
import csv,math
StudentsTXT=open('students.txt')
csv_students=csv.reader(StudentsTXT, delimiter=',')
am =input('please search ip adress')
我也试过这段代码:
import csv,math
StudentsTXT=open('students.txt')
csv_students=csv.reader(StudentsTXT, delimiter=',')
print(csv_students['013'])
但是这个出现错误说:对象没有属性' getitem '
如何将其中一个代码打印出已翻译成csv的文本文件行。
Text文件看起来像这样
010,Jane,Jones,30/11/2001,32|Ban Road,H.Num:899 421 223,Female,11Ca,JJ@school.com
012,John,Johnson,23/09/2001,43|Can Street,H.Num:999 123 323,Male,11Ca,JoJo@school.com
025,Jack,Jackson,29/02/2002,61|Cat grove,H.Num:998 434 656,Male,11Ca,JaJa@school.com
我希望能够搜索任何学生的任何名字,然后打印所有相关信息。
答案 0 :(得分:0)
问题:我希望它能打印出类似的内容:
002,John,Smith,01/01/2001,1 example road,000 000 000,male,11ca,js@school.com instead of: 001, john 002,jane
更改为csv.DictReader
,例如:
注意:假设您在CSV文件中有 NO 标题!
with open('students.txt') as fh:
# Define Header Fieldnames
fieldnames = ['Name', 'SName', 'ID', 'Date', 'Address', 'Kontakt', 'F/M', 'Class', 'EMail']
csv_students = csv.DictReader(fh, fieldnames=fieldnames)
# Iterate csv_students
for student in csv_students:
# Create a List of Data Ordered using Fieldnames
student_list = [student[f] for f in fieldnames]
print('{}'.format(', '.join(student_list)))
# Print only Part of the Fields
print('{s[ID]}: {s[Name]} {s[Address]}'.format(s=student))
输出:
Jane, Jones, 010, 30/11/2001, 32|Ban Road, H.Num:899 421 223, Female, 11Ca, JJ@school.com 010: Jane 32|Ban Road John, Johnson, 012, 23/09/2001, 43|Can Street, H.Num:999 123 323, Male, 11Ca, JoJo@school.com 012: John 43|Can Street Jack, Jackson, 025, 29/02/2002, 61|Cat grove, H.Num:998 434 656, Male, 11Ca, JaJa@school.com 025: Jack 61|Cat grove
使用Python测试:3.4.2