- StringIO
It implements a file-like class that reads and writes a string buffer (also known as memory files).
For example,
there is src.csv file.
src.csv
20,40
50,90
77,22
Run this code that read csv file.
def execute(f):
result = []
reader = csv.reader(f)
for line in reader:
one = int(line[0])
two = int(line[1])
three = one+two
line.append(three)
result.append(line)
return result
with open('src.csv', 'r', encoding='utf-8') as f:
result = execute(f) # 함수실행
print(result)
>>>
[['20', '40', 60], ['50', '90', 140], ['77', '22', 99]]
Using io.StringIO that makes the string to file object and get same result as above.
import csv
import io
def execute(f):
result = []
reader = csv.reader(f)
for line in reader:
one = int(line[0])
two = int(line[1])
three = one+two
line.append(three)
result.append(line)
return result
src = '''\
20,40
50,90
77,22
'''
with io.StringIO(src) as f: # 문자열을 파일객체럼 만든다.
result = execute(f)
print(result)
>>>
[['20', '40', 60], ['50', '90', 140], ['77', '22', 99]]
'Basic Python' 카테고리의 다른 글
cv2.imread (0) | 2024.02.28 |
---|---|
argparse (0) | 2023.12.13 |
Logger, Handler, Filter, Formatter (0) | 2023.12.08 |
str VS repr (0) | 2023.11.16 |
getattr (0) | 2023.11.15 |