Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

How to find string in CSV file python-3

I have a program that takes file code as input in this case '19E071OE1' and it needs to print out all the rows that have that value in its 4th column it kind of works but I have to input file code for each individual row. My question is how do I make it scan all rows at once and print them out?

Code:

import csv


def ime_predmeta():
    imepred = input("Unesi kod predmeta: ")
    if imepred.isupper():
        return imepred
    else:
        print("Unos nije validan probajete opet!")
        return ime_predmeta()


def ucitavanjerasp1():
    file = open('raspored1.csv', "r")
    reader = csv.reader(file, delimiter=',')
    for row in reader:
        if ime_predmeta() in row[3]:
            print(row)


def main():
    ucitavanjerasp1()


if __name__ == '__main__':
    main()

The bad output:

Unesi kod predmeta: 19E071OE1
['0', '08:00', '11:00', '19E071OE1 [OO 2019] P1']
Unesi kod predmeta: 19E071OE1
['0', '11:00', '14:00', '19E071OE1 [OO 2019] P2']
Unesi kod predmeta: 19E071OE1
['0', '14:00', '17:00', '19E071OE1 [OO 2019] P3']
Unesi kod predmeta: 19E071OE1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can achieve that by using regex split method like

with open('raspored1.csv', "r") as f:
    content = f.read()
    print(re.split(f'.*,.*,.*,.*{imepred}.*',content))

this will return you a list with all lines that contain imepred value init in the 4 column.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...