You can convert a string to a file object using io.StringIO and then pass that to the csv module:
from io import StringIO
import csv
scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
gęś,zółty,wąż,idzie,wąską,dróżką,
"""
f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
print('\t'.join(row))
simpler version with split() on newlines:
reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
print('\t'.join(row))
Or you can simply split() this string into lines using \n as separator, and then split() each line into values, but this way you must be aware of quoting, so using csv module is preferred.
On Python 2 you have to import StringIO as
from StringIO import StringIO
instead.
Answer from Michał Niklas on Stack OverflowYou can convert a string to a file object using io.StringIO and then pass that to the csv module:
from io import StringIO
import csv
scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
gęś,zółty,wąż,idzie,wąską,dróżką,
"""
f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
print('\t'.join(row))
simpler version with split() on newlines:
reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
print('\t'.join(row))
Or you can simply split() this string into lines using \n as separator, and then split() each line into values, but this way you must be aware of quoting, so using csv module is preferred.
On Python 2 you have to import StringIO as
from StringIO import StringIO
instead.
Simple - the csv module works with lists, too:
>>> a=["1,2,3","4,5,6"] # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> x = csv.reader(a)
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]
Function to read csv string
python - Parsing CSV string with CSV module - Stack Overflow
Parsing a csv file with specific criteria
When using reader or DictReader from the csv module, why do you need to access the return value while the file is still open?
Videos
I am trying to create a function which takes a string input in csv format. For example ```"id,name,age,score\n1,Jack,NULL,12\n17,Betty,28,11" ```.
It should return the follow table
| id | name | age | score |
|---|---|---|---|
| 1 | Jack | NULL | 12 |
| 17 | Betty | 28 | 11 |
It should also remove the defective rows. A defective row is when it has value **NULL**. sensitive to capital letters. any other characters like (0 to 9 or a to z or A to Z) is acceptable.
The final output from the above input string should be
| id | name | age | score |
|---|---|---|---|
| 17 | Betty | 28 | 11 |
Here is my code using ```pandas and csv``` packages. I need to create this without using any of these packages.
```
def test(S):
result = pd.DataFrame(csv.reader(S.splitlines()))
new_header = result.iloc[0]
result = result[1:]
result.columns = new_header
df = result.select_dtypes(object)
new_result = ~df.apply(lambda series: series.str.contains('NULL')).any(axis=1)
f_result = result[new_result]
return f_result
```