-2

I have a csv (input.csv) file as shown below:

VM IP Naa_Dev Datastore
vm1 xx.xx.xx.x1 naa.ab1234 ds1
vm2 xx.xx.xx.x2 naa.ac1234 ds1
vm3 xx.xx.xx.x3 naa.ad1234 ds2

I want to use this csv file as an input file for my python script. Here in this file, first line i.e. (VM IP Naa_Dev Datastore) is the column heading and each value is separated by space.

So my question is how we can use this csv file for input values in python so if I need to search in python script that what is the value of vm1 IP then it should pickup xx.xx.xx.x1 or same way if I am looking for VM which has naa.ac1234 Naa_Dev should take vm2.

I am using Python version 2.7.8

Any help is much appreciated.

Thanks

2

4 Answers 4

0

Working with tabular data like this, the best way is using pandas.

Something like:

import pandas
dataframe = pandas.read_csv('csv_file.csv')

# finding IP by vm
print(dataframe[dataframe.VM == 'vm1'].IP)
# OUTPUT: xx.xx.xx.x1

# or find by Naa_Dev
print(dataframe[dataframe.Naa_Dev == 'xx.xx.xx.x2'].VM)
# OUTPUT: vm2
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this exactly matches to my requirements.
0

For importing csv into python you can use pandas, in your case the code would look like:

import pandas as pd
df = pd.read_csv('input.csv', sep=' ')

and for locating certain rows in created dataframe you can multiple options (that you can easily find in pandas or just by googling 'filter data python'), for example:

df['VM'].where(df['Naa_Dev'] == 'naa.ac1234')

Comments

0

Use the pandas module to read the file into a DataFrame. There is a lot of parameters for reading csv files with pandas.read_csv. The dataframe.to_string() function is extremely useful.

Solution: # import module with alias 'pd' import pandas as pd

# Open the CSV file, delimiter is set to white space, and then
# we specify the column names.
dframe = pd.read_csv("file.csv",
                     delimiter=" ",
                     names=["VM", "IP", "Naa_Dev", "Datastore"])
# print will output the table
print(dframe)

# to_string will allow you to align and adjust content
# e.g justify = left to align columns to the left.
print(dframe.to_string(justify="left"))

Comments

0

Pandas is probably the best answer but you can also:

import csv
your_list = []
with open('dummy.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=' ')
    for row in reader:
        your_list += [row]
print(your_list)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.