Part 2 of Python CSV Output (Reading Data for the )

Asked 2 years ago, Updated 2 years ago, 33 views

Regarding the CSV output that I asked you about the other day (Last question link), I did not understand it, but I did not understand it.

I don't think this will improve, so I understand text processing, loops, lists, etc. well
I would like to improve even a little, so I would like to ask you a question again.
(The answers and advice from everyone the other day were too high for me...)

Therefore, I managed to deal with the following conditions (1) and (2) in my own way, but
I don't know how to convert the results into CSV format.
Should I use a dictionary format, or should I use loop processing when using a dictionary format?
Or should I split it with :, and so on? From here, how
I don't know if I should use CSV format.
Therefore, I would appreciate it if you could advise me again.

Conditions
①There is one interface in the system:deleting the
③Convert name to profile name to CSV format and save as sample.csv

The system has one interface:

    Name: Wi-Fi
    Description: Qualcomm Atheros QCA 61x4A Wireless Network Adapter
    GUID: 0000000000000000000000
    Physical address: xx: xx: xx: xx: xx: xx: xx
    Conditions: Connected
    BSSID:xx:xx:xx:xx:xx:xx:xx
    network types:infrastructure
    Radio Type: 802.11n
    authentication:WPA2-Personal
    ciphers:CCMP
    connection modes:automatic connection
    Channels: 6
    Receive Speed (Mbps): 144.4
    Transmission speed (Mbps): 144.4
    Signals: 94%
    profiles:sample-wifi

    Hosted Network Status: Not Available
#readlines() to load in list format

with open('example.txt', encoding='utf-8') asf:
    contents=f.readlines()

# システム There is one interface in the system:
# ホスト Status of hosted networks: Not available
# In order to delete , confirm the number of items listed above (i) and (ii)

count = 0
For line in contents:
    print(f"{count}->{line.strip()}")
    count+=1

# ② は will be the 0th and 19th, so other than that,
# Display (to retrieve) for new_line in contents [2:18].

for new_line in contents [2:18]:
    print(new_line.strip())

python python3

2022-09-30 14:34

2 Answers

# システム There is one interface in the system:
# ホストState of hosted network: Not available
# In order to delete , check the number of items listed above ②2

For Python, you can specify a negative integer value for the index of the list.The meaning is from the end of the list to the top.

>>>lst=[1,2,3,4,5,6]
>>>>lst[-1]# trailing element
6
>>>lst[-2]#Second element from tail to top
5
>>>lst[2:-2]# From "Third element from top" to "Third element from bottom to top"
[3, 4]

In other words, even if you write the following, the result will be the same.

with open('example.txt', encoding='utf-8') asf:
    contents=f.readlines()

for new_line in contents [2:-2]:
    print(new_line.strip())

However, considering the output format of the netsh wlan show interface command, we will extract areas separated by blank lines, so we can also write as follows.In this case, the contents of contents will be a string containing a new line code, not a list.

import re

with open('example.txt', encoding='utf-8') asf:
  contents=f.read()

contents=re.split(r'\r?\n\r?\n', contents)[1]

ConfigParser

I don't know how to convert the results into CSV format.

The output of the netsh command is basically structured similar to the Windows INI file.The difference is that the INI file displays the parameters in name=value format, but netsh shows property:value.Also, the INI file has a section ([group_name]), but not in netsh.There are other differences, but I will not mention them as they will not affect this case.

Python provides a module for parsing files that have a similar structure to this INI file.

configparser --- configuration file parser

This module provides a ConfigParser class that implements a basic configuration language with a structure similar to the Microsoft Windows INI file.Use this class to create a Python program that users can easily customize

Here is an example implementation for this case:

import configparser
import csv
import re

with open('example.txt', encoding='utf-8') asf:
    contents=f.read()

# Extract Name to Profile
contents=re.split(r'\r?\n\r?\n', contents)[1]

dummy='dummy'
# Set delimiter to:(colon)
parser=configparser.RawConfigParser(delimiters=(':'))
# The contents do not have a "section" like the INI file.
# Add dummy section
parser.read_string(f'[{dummy}]\n'+contents)
# Swap rows and columns (transpose)
table=[*zip(*(parser[dummy].items()))]

# Save in CSV format
with open('sample.csv', 'w', encoding='utf-8') asc:
  cw=csv.writer(c,quoting=csv.QUOTE_MINIMAL)
  cw.writerows(table)

sample.csv


2022-09-30 14:34

It seems that は and てる are ready, so I will think about using the code up to that point.

The line
Name: Wi-Fi corresponds to CSV. It is separated like "One column in the header row: One column in the data row".
When outputting the final output, it is output in two separate lines, so consider separately.
We aim to create this kind of data.

header_list=["Name", "Description", "GUID" ]
data_list = ["Wi-Fi", "Qualcomm Atheros QCA61x4A Wireless Network Adapter", "00000000000000000000" ]

Once these two lists are completed, the CSV output should be concatenated with ", "

print(", ".join(header_list))
print(", ".join(data_list))


New_line "Name: Wi-Fi" loaded in one line in the for loop. If you think about how to divide it into "Name" and "Wi-Fi", you can see that it is divided by ":".
You can use split to separate them

header = 0th divided by new_line.split(":")[0]#:
data=new_line.split(":")[1]#—First divided by

Let's see if it's split up.

 for new_line in contents [2:18]:
    new_line = new_line.strip()
    header = new_line.split(":")[0]
    data=new_line.split(":")[1]
    print(f"header={header}/data={data}")

This output shows that there is an extra blank space.

"header=name/data=Wi-Fi"

Remove this with strip as well.

header=new_line.split(":")[0].trip()
data=new_line.split(":")[1].trip()

If you look at it, the physical address part is shortened because the data contains ":".

header=physical address/data=xx

If you want to split, use the argument maxsplit that specifies how many times you want to split it.

header=new_line.split(":", 1)[0].trip()
data=new_line.split(":", 1)[1].trip()

Now the split is done correctly.

header=physical address/data=xx:xx:xx:xx:xx:xx:xx:xx

I will put this in the header_list, data_list.

header_list=[]
data_list = [ ]
for new_line in contents [2:18]:
    new_line = new_line.strip()
    header = new_line.split(":", 1)[0].trip()
    data=new_line.split(":")[1].trip()
    print(f"header={header}/data={data}")

    header_list.append(header)
    data_list.append(data)

Now that I can separate CSV columns from header and data rows, all I have to do is output them!

The code is a little redundant to understand how to output in CSV format.
I think it would be easier to write using the library, but I didn't use the library because I think the question this time is to understand the algorithm.
Personally, judging 、 and も by line numbers is a problem when the number of lines changes, so I thought it would be better to exclude them from the included strings.


2022-09-30 14:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.