将文本文件更改为csv(多行)

2024-04-24 05:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个txt文件,内容如下:

interface 0/1
no data
no data
no data
no data
no data
interface 0/2
no data
etc...

我想将其输出到csv格式:

interface 0/1 | no data | no data | no data | no data | no data
interface 0/2 | no data | no data | no data | no data | no data

我试过使用csv模块和写行没有好的结果。任何帮助都将不胜感激。你知道吗


Tags: 模块文件csvnotxt内容data格式
3条回答

您也可以尝试不使用csv模块:

f = open("file.txt", "r")
of = open("file.csv", "w")

data = f.readlines()
checkpoint = ""

for line in data:
    line = line.strip("\n")
    if "interface" in line:
        of.write(checkpoint + line)
        checkpoint = "\n"
    else:
        of.write(" | " + line)

f.close()
of.close()

下面是一个简单的、略有不同的答案,它只使用python2.7(没有csv)

f=open("data.txt", 'r')  # original data
f1=open("output_data.txt", 'w')   # this is to write the output
newline=""
for line in f:
    if "interface" not in line:
        newline=newline + r" |  " + line.strip()
    else:
        # print newline # check this
        f1.write(newline + '\n')
        newline=line.strip()
# print newline # just a visual check
f1.write(newline)

看起来您想将6行组合成一行,然后将它们写入,例如:

import csv
from itertools import islice

with open('input.txt') as fin, open('output.csv', 'w') as fout:
    pipe_out = csv.writer(fout, delimiter='|')
    rows = iter(lambda: list(islice(fin, 6)), [])
    pipe_out.writerows(rows)

相关问题 更多 >