Python编码TextFile,将其打开,替换多个部分和输出,而无需为.CSV样式格式的文本而没有空线



我拥有的是" 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(FlatFile),以后可以将其导入到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)

但是文件看起来相同,要么完全为空

摆脱空线:

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)

输出

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

编辑

也许是从文件中读取然后使用存储结果的列表来覆盖该文件。

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!

最新更新