如何从现有的python文件导入数据以在python 3中写入新的csv文件

时间:2018-11-26 03:47:33

标签: python-3.x csv networking topology

例如,这是我的python文件,即client.py,我希望将数据(在此文件中生成的ID,Ip_add,mac_address导出到新的csv文件中)。

#client.py
import random
import socket

# funtion to define no. of switch

def switch_info(no_of_switch):

    for number in range (1,no_of_switch+1):
        print("ID:s",+number)

        ip_add = '127.0.0.' + str(random.randint(0, 255))
        print("IP_address:{}".format(ip_add))

        mac_add = "-".join(map(str,(random.randint(0,255)for _ in range(4))))
        print("Mac_address:{}".format(mac_add))
        print('\n')
switch_info(2)

1 个答案:

答案 0 :(得分:0)

像这样吗?

client.py

import numpy as np
ids = []
ip_addr = []
mac_addr = []

def switch_info(no_of_switch):
    for number in range (1,no_of_switch+1):
        print("ID:s",+number)
        ids.append(number)

        ip_add = '127.0.0.' + str(np.random.randint(0, 255))
        ip_addr.append(ip_add)
        print("IP_address:{}".format(ip_add))

        mac_add = "-".join(map(str,(np.random.randint(0,255)for _ in range(4))))
        print("Mac_address:{}".format(mac_add))
        mac_addr.append(mac_add)
        print('\n')
    return ids, ip_addr, mac_addr

new_file.py

import pandas as pd
from client import switch_info

ids, ip_addr, mac_addr = switch_info(5)

df = pd.DataFrame()
df["Id"] = ids
df["IP"] = ip_addr
df["MAC"] = mac_addr
print(df)
df.to_csv("network.csv", index=False)

输出:

   Id           IP             MAC
0   1  127.0.0.243  189-65-170-107
1   2  127.0.0.199    137-20-84-43
2   3  127.0.0.237  215-155-12-163
3   4  127.0.0.251  224-213-118-35
4   5  127.0.0.117  186-230-124-75