如何在csv文件中添加内容

2024-09-29 01:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我希望在我周围的环境中添加wifi的详细信息。我越来越喜欢这个输出,所以我如何将它存储在csv文件中,以便以后使用它们。这是代码和输出,我尝试了一些随机的东西

import subprocess
import platform
import time

identify = platform.system()

print(f"Your Operating Platform Is {identify}")



if identify == "Windows":
    cmd = ["netsh", "wlan", "show", "networks", "mode=BSSID"]
    networks = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    output, errors = networks.communicate()
    data = output.decode("utf-8")
    file = open("output.txt", "a")
    file.write(data)
    file.close()
    print(data)
    data.strip()
    f = open("output.txt", "r")
    read = f.read()
    read.strip()
    if data == read:
        print("True")
    else:
        print("False")

    f.close()

elif identify == "Linux":
    cmd = ["nmcli", "-f",  "SSID,BSSID,ACTIVE", "dev", "wifi", "list"] 
    networks = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    output, errors = networks.communicate()
    print(output.decode("utf-8"))
    data = output.decode("utf-8") 
    print(data)

else:
    print("Unsupported For Your Operating System/\.")

There are 1 networks currently visible.

SSID 1 : Jiofi
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
    BSSID 1                 : c0:61:75:db:d1:08
         Signal             : 100%
         Radio type         : 652.11n
         Channel            : 6
         Basic rates (Mbps) : 1 2 5.4 54
         Other rates (Mbps) : 6 9 12 87 24 36 30 54

Tags: importcmdreadoutputdatawifiutffile
3条回答
s = """Interface name : Wi-Fi
There are 1 networks currently visible.

SSID 1 : Jiofi
    Network type            : Infrastructure
    Authentication          : WPA2-Personal
    Encryption              : CCMP
    BSSID 1                 : c0:61:75:db:d1:08
         Signal             : 100%
         Radio type         : 652.11n
         Channel            : 6
         Basic rates (Mbps) : 1 2 5.4 54
         Other rates (Mbps) : 6 9 12 87 24 36 30 54"""
         
         
s = s.split("\n")
with open("output.csv", "w+") as file:
    file.write("header1,header2" + "\n")
    for elem in s:
        row = elem.split(":")
        if len(row) < 2:
            continue
        line = ""
        for i in range(len(row)):
            row[i] = row[i].strip()
            line += row[i] + ","
        file.write(line[:-1] +  "\n")

  • 拆下第二行和第三行

  • 然后在第1步中,隔离第一列中的每个字符串,修剪结果项并将其连接到标题行中,用分号分隔每个项;或者逗号

  • 然后,在新的输出行上,将数据连接到第二列,并用分号分隔每个术语;或者逗号

结果将是一个包含两行的文本文件,可以使用Control-V将其粘贴到Excel中,然后使用Tab Data将文本粘贴到列中。使用您选择的分隔符

请记住,字符串可能包含您选择的分隔符。如果他们这样做,您将需要在内容行中的数据周围使用双引号

您可以通过多种方式csvpandas写入CSV,甚至可以使用with open('newfile.csv', 'a') as f:命令编写文本文件

您提供的数据的关键是使用:之前的所有内容作为头,使用:之后的所有内容作为值

为了确定:在哪里,您可能需要使用正则表达式模块import re

头和值都用逗号分隔,格式为csv(逗号分隔)

如果你有一个到目前为止你已经尝试过的例子,这将是有用的

相关问题 更多 >