0

So i have a text file containing:

 , "Hi, I am Jane",,"Thirty two"
"2", "Mr P","X","Fifty"

and I'm reading the text file into python and appending them into a list(splitting by comma not in quotes) to get:

[['','"Hi, I am Jane",'','"Thirty two"'],['"2"', '"Mr P"', '"X"', '"Fifty"']]

The file basically have four columns, and that the first line, you could see that it begins with a comma, is because there is no first field hence having ' ' in the output list is wanted. Where as in the second line, it is a complete line with four fields.

I attempted:

filename = open("mytext.txt", "r")
f = filename.readlines()
wlst = []

for line in f:
   line = line.strip('\n')
   line = line.split(',')
   wlst.append(line)

print(wlst)

But the output shows:

[['','"Hi', ' I am Jane"', '', '"Thirty two"'],['"2"', ' "Mr P"', ' "X"', ' "Fifty"']]

The "Hi" segment has been separated with the "I am Jane" segment. I would like to know how to split by comma, ignoring the ones in the quotes? I've seen previous post on something like this, but apparently none of the solutions work for reading in text files.

Maxxx
  • 3,688
  • 6
  • 28
  • 55
  • 2
    use csv module. Does this answer your question? [How do I read and write CSV files with Python?](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – buran Mar 07 '20 at 15:54
  • @buran it's not an excel csv file! It is a txt file. – Maxxx Mar 07 '20 at 15:58
  • 1
    as I said use csv module. that is exactly what it is. the file extension doesn't matter - txt or csv. And there is no such thing as csv excel file :-). – buran Mar 07 '20 at 16:00
  • @Maxxx Yes it has a .txt file extension, but it's in CSV format. Excel has nothing to do with this; you might be confused because Excel *can open* CSV files. – wjandrea Mar 07 '20 at 16:36
  • 1
    @wjandrea Actually, CSV files can have Excel-specific formatting, and Python has [explicit support for that](https://docs.python.org/3/library/csv.html#csv.excel). – ekhumoro Mar 07 '20 at 16:44

0 Answers0