I have some tab-delimited text files, formatted in several different ways, which I am exporting into Excel using Python. Most of the lines end with cells formatted like this:
'TEMP1', '\r\n'
but a handful of them are formatted like this instead:
'TEMP1\r\n'
Python is not getting the entries that are formatted in the second way. Any way around this? Here’s my code:
for line in current_file:
try:
a = line.split("\t")
for col in range (1, len(a)):
xlSheet.Cells(output_row, col).Value = a[col - 1]
output_row += 1
except ValueError:
pass
Since it seems like you are using
len(a)as a way to referencing the column number, I would suggest usingenumerate, which returns the index of the item. Your current issue is that you aren’t including the last item in your range, which is fine in cases where the last items is a line break. One thing you could try is stripping each line, which would remove the newlines: