I'm trying to edit a csv file (in place would be preferrable). I've tried multiple things with various modules. I've given up at this point.
Original file:
A,B,sometext_1_sometext,C,D
E,F,sometext_2_sometext,G,H
I,J,sometext_3_sometext,K,L
...
Desired result:
A,B,ONE,C,D
E,F,TWO,G,H
I,J,THREE,K,L
import os
import csv
import pandas as pd
infile = 'Infrastructure.csv'
df = pd.read_csv('Infrastructure.csv')
with open('Infrastructure.csv', 'r') as f:
reader = csv.reader(f)
for line in reader:
for i, row in enumerate(reader):
for j, column in enumerate(row):
if "IOS" in column:
if "XE" in column:
#print(f"XE{(i,j)}")
df.loc[(i), 2] = ",cisco_xe"
else:
#print(f"IOS{(i,j)}")
df.loc[(i), 2] = ",cisco_ios"
if "NX" in column:
#print(f"NX{(i,j)}")
df.loc[(i), 2] = ",cisco_nxos"
if "JUNOS" in column:
#print(f"JUNOS{(i,j)}")
df.loc[(i), 2] = ",juniper_junos"
Answer
Are you overthinking it? Can you just do global find-and-replace for the values you care about?
Given your sample data, this does something similar to what you're asking for. (Remember, you asked for it to work "in place would be preferrable" so this is destructive to the input file.)
replacements = {
"sometext_1_sometext" : "ONE",
"sometext_2_sometext" : "TWO",
"sometext_3_sometext" : "THREE"
}
with open('Infrastructure.csv', 'r+') as file:
data = file.read()
for old, new in replacements.items():
data = data.replace(old, new)
file.seek(0)
file.truncate()
file.write(data)