0

I am new to python. I have a text file as 'asv.txt' having the following content:

[['10', '50', '', ' Ind ', '', ''], ['40', '30', '', ' Ind ', 'Mum', ''], ['50', '10', '', ' Cd ', '', '']]

How do I read it as a csv or as a dataframe.

some_programmer
  • 3,268
  • 4
  • 24
  • 59
sak
  • 59
  • 4

1 Answers1

0
# Read file (or just copy text)
with open('asv.txt') as f:
    data = f.read()

# Convert str to list with ast
import ast
data = ast.literal_eval(data)

## Load dataframe using the "data" argument, which can accept a list and treats it as rows
df = pd.DataFrame(data=data)

Or much simpler for this specific case:

df = pd.DataFrame(data=[['10', '50', '', ' Ind ', '', ''], ['40', '30', '', ' Ind ', 'Mum', ''], ['50', '10', '', ' Cd ', '', '']])
  • I used the above code for my text file but I'm getting this error: '(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape' – sak Sep 09 '20 at 10:07
  • https://stackoverflow.com/questions/1347791/unicode-error-unicodeescape-codec-cant-decode-bytes-cannot-open-text-file – Ilai Waimann Sep 09 '20 at 13:04