将文本文件中的行写入.csv文件

时间:2018-08-29 21:37:33

标签: python python-3.x

我有以下代码可创建一个csv文件(sw_mac_addr.csv)。现在,它会写我想要的每一行。我需要用逗号(,)分隔值。

infile中的一行如下所示: * 51 0000.0c9f.f033 static 0 F F sup-eth2

我希望它像这样出现在csv文件中: 51,0000.0c9f.f033,sup-eth2

import os
path = 'c:/sw_mac_addr/'
fh = open("C:/Users/cslayton2/Documents/sw_mac_addr.csv", "w+")
print('Switch Name', 'Port', 'mac addr', 'vlan', sep=",", file=fh)

for filename in os.listdir(path):
    with open(os.path.join(path,filename), "r") as infile:
        for line in infile:
            if line.startswith('*') or line.startswith('+'):
                fh.write(line)
fh.close()

2 个答案:

答案 0 :(得分:0)

熊猫可以做到这一点

import pandas as pd

df = pd.read_csv('c:/sw_mac_addr/mycsv.csv', sep=',')
df.to_csv('c:/sw_mac_addr/test.txt')

答案 1 :(得分:0)

import os
path = './text/'
# open this file for writing
with open("sw_mac_addr.csv", "w+") as fh:
    print('Switch Name', 'Port', 'mac addr', 'vlan', sep=",", file=fh)
    # get data from all files in the path
    for filename in os.listdir(path):
        with open(os.path.join(path,filename), "r") as infile:
            for line in infile:
                if line.startswith('*') or line.startswith('+'):
                    # if you want to get rid of the * and +, uncomment the following code
                    # line = line.replace("*","").replace("+","")
                    line = ",".join(line.split()) + "\n"
                    fh.write(line)
                    print(line)

输出(在控制台和csv文件上):

*,51,0000.0c9f.f033,static,0,F,F,sup-eth2

*,51,0000.0c9f.f033,static,0,F,F,sup-eth2

*,51,0000.0c9f.f033,static,0,F,F,sup-eth2

输出不带注释的代码行(line = line.replace(“ *”;“”)。replace(“ +”,“”)

51,0000.0c9f.f033,static,0,F,F,sup-eth2

51,0000.0c9f.f033,static,0,F,F,sup-eth2

51,0000.0c9f.f033,static,0,F,F,sup-eth2