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

时间:2017-08-03 20:01:11

标签: python csv

我有一个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模块并写入没有好结果的行。任何帮助将不胜感激。

6 个答案:

答案 0 :(得分:0)

看起来你想将6行分成一行并写下来,例如:

        string description = null;
        using (DataConnection connection = new DataConnection())
        {
            var mediaFile = connection
                .Get<IMediaFile>()
                .Where(m => m.Id == pictureId)
                .FirstOrDefault();
            if(null != mediaFile)
            {
                description = mediaFile.Description;
            }
        }

答案 1 :(得分:0)

这是一个简单的,略有不同的答案,只使用python 2.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)

答案 2 :(得分:0)

您也可以在没有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()

答案 3 :(得分:0)

通常不需要CSV模块。这个脚本就可以了。

f1 = open('file1.txt', 'r')
f2 = open('file2.csv', 'w+')

lines = f1.read()
for line in lines.split('\n'):
    if line == "":
        continue
    elif line.startswith("interface"):
        f2.write("\n"+line+",")
    else:
        f2.write(line+",")

答案 4 :(得分:0)

我这样做了:

content = ''
with open('text_file.txt', 'r') as txt_file:
  content = txt_file.read()

blocks = content.split('interface')

csv_content = ''
for block in blocks:
  if block != '':
    csv_content += 'interface %s\n' % ' | '.join(block.splitlines())

with open('csv_file.csv', 'w') as csv_file:
  csv_file.write(csv_content)

答案 5 :(得分:0)

可以通过从文件中的每一行收集一行数据,并在遇到以'interface'开头的行时将其输出为csv行:

import csv

input_filename = 'interface.txt'
output_filename = 'interface.csv'

with open(input_filename) as infile, \
     open(output_filename, 'w', newline='') as outfile:

    writer = csv.writer(outfile, delimiter='|')
    row = []

    for line in (line.rstrip() for line in infile):
        if not line.startswith('interface'):
            row.append(line)
        else:  # new group
            if row:
                writer.writerow(row)  # output last group
            row = [line]

    writer.writerow(row)  # output last row

之后interface.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