简体   繁体   中英

Pyscripter and printing line of CSV file

Here is my code:

 import csv,math
 StudentsTXT=open('students.txt')
 csv_students=csv.reader(StudentsTXT, delimiter=',')
 am =input('please search ip adress')

I also tried this code :

 import csv,math
 StudentsTXT=open('students.txt')
 csv_students=csv.reader(StudentsTXT, delimiter=',')
 print(csv_students['013'])

But this one comes up with error saying:object has no attribute' getitem '

How can I make one of these codes to print out line of my text file already translated into csv.

The Text file looks something like this

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

I want to be able to search for any of the names of any students and then print all information about them .

Question : i want it to print things like for example:

 002,John,Smith,01/01/2001,1 example road,000 000 000,male,11ca,js@school.com instead of: 001, john 002,jane 

Change to csv.DictReader , for instance:

Note : Assuming you have NO Headers in the CSV File!

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))

Output :

 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 

Tested with Python: 3.4.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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