I have many .csv files which looks like
header01,header02,header03,
data01,data02,data03,
data11,data12,data13,
data21,data22,data23,
data31,data32,data33,
I need an short function with that I can overwrite the [1] cell in the data section from data02 to something like test_data02. I need to replace a big amount of cells in csv-files with that method, maybe I can read the line line in the file and save it as new one, so I knew it's definitely done.
CodePudding user response:
You can use pandas library to work with csv's it's much simple.
So you open your csv :
df = pandas.read_csv('your_file.csv')
Get your cell value with :
value = df.iloc[i]['header02']
Where i
is your row number
Then you can change any cell with this command :
df.set_value(i, 'header02', 'test_' value)
Your first parameter is the row number, second is column name and third is the replacement value
CodePudding user response:
data =[]
path = 'test.csv'
with open (path,'r') as csvfiler:
for i, line in enumerate(csvfiler):
if i != 0:
i-=1
line = line.split('\n')[0].split(',')
line[1]="test_data" str(i) "2"
line=','.join(line)
line ="\n"
data.append(line)
with open (path,'w') as csvfilew:
for line in data:
csvfilew.write(line)