繁体   English   中英

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

[英]Write lines from text file into .csv file

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

infile中的一行如下所示: * 51 0000.0c9f.f033 static 0 FF 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()

熊猫可以做到这一点

import pandas as pd

df = pd.read_csv('c:/sw_mac_addr/mycsv.csv', sep=',')
df.to_csv('c:/sw_mac_addr/test.txt')
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM