import csv from io import StringIO data = "name,age\nJohn,25\nMary,30\n" stream = StringIO(data) reader = csv.reader(stream) for row in reader: print(row)
['name', 'age'] ['John', '25'] ['Mary', '30']
from io import StringIO def process_file(file): for line in file: print(line) data = "Hello\nWorld\n" stream = StringIO(data) process_file(stream)
Hello WorldIn this example, we defined a function that expects a file object as input. We then created a string containing some data and used StringIO to create a file-like object from it. We then passed this object to the function and looped through the lines. Package library: io (standard library)