python - 将文本文件中的行写入 .csv 文件
问题描述
我有以下创建 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()
解决方案
熊猫可以很好地做到这一点
import pandas as pd
df = pd.read_csv('c:/sw_mac_addr/mycsv.csv', sep=',')
df.to_csv('c:/sw_mac_addr/test.txt')