Max Sh
Max Sh

Reputation: 109

Are any way to use read_csv without creating files? Using StringIO

Is any pretty way to create DataFrame without creating file, using StringIO?

import pandas as pd

Data=["Header\n","one\n", "two\n", "three\n"]
with open ("chat1.tmp", "w", encoding="utf-8")  as handle:
    handle.writelines(Data)
df = pd.read_csv("chat1.tmp", delimiter='~',  error_bad_lines=False, dtype = str)

I want to leave handle.writelines() for debugging proposes.

Upvotes: 0

Views: 173

Answers (1)

jezrael
jezrael

Reputation: 863176

Use StringIO with join:

from io import StringIO

Data=["Header\n","one\n", "two\n", "three\n"]

df = pd.read_csv(StringIO(''.join(Data)), sep='~',  error_bad_lines=False, dtype = str)

print (df)

  Header
0    one
1    two
2  three

If need write data from list in loop:

from io import StringIO

Data=["Header\n","one\n", "two\n", "three\n"]

output = StringIO()
for val in Data:
    output.write(val)
 
output.seek(0)
df = pd.read_csv(output, sep='~',  error_bad_lines=False, dtype = str)
print (df)
  Header
0    one
1    two
2  three

Upvotes: 1

Related Questions