Python кодирует текстовый файл, открывает его, заменяет несколько разделов и выводит их без пустых строк в виде текста, отформатированного в стиле .csv - PullRequest
0 голосов
/ 15 марта 2019

У меня есть файл "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)

Но файл либо выглядит одинаково, либо полностью пуст

1 Ответ

0 голосов
/ 15 марта 2019

Чтобы избавиться от пустых строк:

list.txt:

Row A;Row B;Row C

New York;23;warm

San Francisco;40;hot

Следовательно

logFile = "list.txt"
with open(logFile) as f:
    content = f.readlines()

# to remove empty lines
content = [l.strip() for l in content if l.strip()]
for line in content:
    print(line)

OUTPUT

Row A;Row B;Row C
New York;23;warm
San Francisco;40;hot

EDIT

возможно, чтобы прочитать из файла и затем перезаписать его, используя список, в котором хранятся результаты, которые впоследствии могут быть записаны в файл.

logFile = "list.txt"                # your file name
results = []                        # an empty list to store the lines
with open(logFile) as f:            # open the file
    content = f.readlines()         # read the lines

# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]   # removing the empty lines
for line in content:
    results.append(line)    # appending each line to the list

print(results)              # printing the list


with open(logFile, "w") as f:    # open the file in write mode
    for elem in results:         # for each line stored in the results list
        f.write(str(elem) + '\n')  # write the line to the file
    print("Thank you, your data was overwritten")  # Tadaa-h!
...