У меня есть файл "test.xls", который в основном представляет собой старый xls (форматирование xml), который в блокноте выглядит следующим образом:
<table cellspacing="1" rules="all" border="1">
<tr>
<td>Row A</td><td>Row B</td><td>Row C</td>
</tr>
<tr>
<td>New York</td><td>23</td><td>warm</td>
</tr>
<tr>
<td>San Francisco</td><td>40</td><td>hot</td>
</tr>
</table>
Теперь я использую Python, чтобы преобразовать его в .txt (плоский файл), который позже я могу импортировать в базу данных MSSQL.
Что у меня есть:
import codecs
import os
# read the file with a specific encoding
with codecs.open('test.xls', 'r', encoding = 'ansi') as file_in, codecs.open('test_out.txt', 'w') as file_out:
lines = file_in.read()
lines = lines.replace('<tr>', '')
# save the manipulated data into a new file with new encoding
file_out.write(lines)
Этот подход приводит к .txt, как это:
Row A;Row B;Row C
New York;23;warm
San Francisco;40;hot
Я пытался избавиться от пустых строк несколькими подходами, последний был:
for lines in file_in:
if line != '\n':
file_out.write(lines)
Но файл либо выглядит одинаково, либо полностью пуст