【问题标题】:how to import data from existing python file to write new csv file in python 3如何从现有的python文件导入数据以在python 3中写入新的csv文件
【发布时间】:2019-04-27 17:03:43
【问题描述】:

例如这是我的 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)

【问题讨论】:

  • 我必须创建一个网络拓扑,其中包括相互连接的交换机、客户端、网关和路由器(个人 ID、ipadd、macadd、状态),然后我必须编写代码来创建csv 文件,其中包含网络中每个参与者的信息......最后我必须通过任何可视化工具展示网络。

标签: python-3.x csv networking topology


【解决方案1】:

这样的?

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

【讨论】:

  • 如果我需要将网关和服务器文件的信息与client_info一样列出到network.csv文件中,不断喜欢。 c1 127.0.0.0 12-45-67 \n c2 128.5.6.7 45-65-7-9 \n s1 127.5.6.7 34-65-87 \n gw1 134.5.6..7 43-56-76 s1-server1 ,c1-client1,gw1-gateway1。我应该每次都制作不同的 Dataframe 对象吗?
猜你喜欢
  • 2016-02-10
  • 2019-06-13
  • 2021-09-26
  • 2017-06-18
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
相关资源
最近更新 更多