Python Forum

Full Version: How to output one value per request of the CSV and print it in another func?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can You please tell me how to do. The first function needs to read USERNAME column from csv file to output one value per request and the second function outputs this value to the console with 5 seconds pause. To cycle through the entire column in the file. Thanks!!
import csv
import time

filename = "D:/Study/file/.vscode/telescript/DarkCryptoMining.csv"

def func1():
    global Field  
    with open(filename, 'r', encoding="utf-8", newline='') as f:
         data = csv.DictReader(f, delimiter=";")
         for str in data:


          for row in data:
             if row['USERNAME'] == "-":
                time.sleep(0)
             else:
                Field = (f'{row["USERNAME"]}')
                
def func2():
   time.sleep(5)
   print(Field)
                
def main():
   func1() 
   func2()               


main()
The main body of your program is going to have a loop where you call func1, which returns a value from the username column, then calls func2 which prints the returned username value and waits 5 seconds.

Do not use global variables to pass information between your functions. Use function arguments to pass a value to a function and use "return value" to return a value from a function.

The tricky part is how to open the CSV file and get the usernames one at a time. Your current solution will not work because each time you call func1 you open the file and return the first name. Are you familiar with generators and the "yield" statement? My guess is yes, since the assignment seems designed to force using a generator.
It's better not to use reserved words when declaring variables, such as for str in data:, because if you need to use the str() function in that loop, you won't be able to.

Such usage can lead to confusion if you've used the likes of str = "Whatever" at some point and need the function further down; an error such as [builtins.TypeError: 'str' object is not callable] could very well throw you for a while, until you figure out what you've done: code blindness sets in, along with some frustration, if you fail to spot the mistake right away -- prevention is better than a cure.
To show with some code what deanhystad talks about.
No global💀 see how arguments are pass to functions.
Your Field varible will never work as will as will only get last execution in loop assigned.
Here wilh yield.
test.csv:
Output:
one,two,three 1,2,3 3,4,5
import csv
import time

def func1(filename):  
    with open(filename, encoding="utf-8", newline='') as f:
        reader = csv.reader(f, delimiter=",")
        for row in reader:
            #print(row[0])
            yield row[0]    

def func2(field):
    time.sleep(5)
    #print(list(field))
    for row in field:
        print(row)

if __name__ == '__main__':
    filename = "test.csv"
    result = func1(filename)
    func2(result)
Output:
one 1 3
Here with a list and append not as elegant as yield in this case.
But you see how this can be used to store result that's done in loop,just a variable in loop will overwrite all but last result.
import csv
import time

def func1(filename):
    field = []
    with open(filename, encoding="utf-8", newline='') as f:
        reader = csv.reader(f, delimiter=",")
        for row in reader:
            #print(row[0])
            field.append(row[0])
    return field      

def func2(field):
    time.sleep(5)    
    #print(field)
    for row in field:
        print(row)

if __name__ == '__main__':
    filename = "test.csv"
    result = func1(filename)
    func2(result)
Output:
one 1 3