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

问题描述 投票:1回答:2

我有以下代码创建一个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()
python python-3.x
2个回答
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')

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
© www.soinside.com 2019 - 2024. All rights reserved.