Home > Enterprise >  Loop through a CSV and extract first 'N' characters and store as variable
Loop through a CSV and extract first 'N' characters and store as variable

Time:10-05

I have a csv file which is one column.

The row is a hostname of a server in the following format DC1-XX-hostname-001 as an example.

What I would like to do is extract the first 3 characters and store in a variable or array 'dc' , then have a variable or array 'vm' which would be the text from each row of the csv

so far I have managed to read the csv and print each line

    import csv

# opening the CSV file
with open('learning python/bulk vm test/vms.csv', mode ='r')as file:
# reading the CSV file
    csvFile = csv.reader(file)
    # read first 3Chars from each line
    dc = ""
    # row value is vm name
    vm = ""
    # fqdn is row value appending domain
    fqdn = vm   "io.local"
# displaying the contents of the CSV file
    for lines in csvFile:

        print(lines)

CodePudding user response:

You can read your CSV file using pandas.read_csv

df = pd.read_csv('learning python/bulk vm test/vms.csv')
dc = df['col_name'].str[:3]
vm = df['col_name'].str   'io.local'

Hope it helps!

CodePudding user response:

IIUC, you are trying to go from a file that has the following format:

DC1-XX-hostname-001
DC1-XX-hostname-002
DC1-XX-hostname-003
...

And get to a structure that is something like this:

[
  ('DC1', 'DC1-XX-hostname-001', 'DC1-XX-hostname-001.io.local'),
  ('DC1', 'DC1-XX-hostname-002', 'DC1-XX-hostname-002.io.local'),
  ...
]

To do this, I don't think you need to process it as a csv, because it is only one column:

with open('myfile.csv') as fh:
    values = []

    # iterate over the file directly
    for vm in fh:
        vm = vm.strip('\n,') # strip off newlines and potential delimiter
        dc, fqdn = vm[:3], f"{vm}.io.local"
        # store the dc, vm name, and fqdn
        values.append((dc, vm, fqdn))
  • Related