Home > OS >  Modifying all values Excel/CSV
Modifying all values Excel/CSV

Time:10-05

I have an issue and I'm not sure how to handle it.

I have a Excel/CSV file and I need to modified it. I need to add quotation marks to all the cells.

This is what I have

Matter,TK,FeedT,Blank1,Blank2,Date,Time,Blank3,Blank4,Description

This is what I need

"Matter","TK","FeedT","Blank1","Blank2","Date","Time","Blank3","Blank4","Description"

Any suggestion on where to look?

CodePudding user response:

Try something like this:

cells = line.split(',')
line = ''
for cell in cells
    line = '"'   cell   '",'
if line[-1] == ','
    line = line[0:line.len() - 1]

CodePudding user response:

This solution should take you from the reading of the file to the rewriting of it, if that is your aim.

newFile = ""
with open('some.csv', "r") as csv_file:
    for row in csv_file:
        entries = row.split(",")
        result = list(map(lambda x: '"'   x   '"', entries))
        newFile  = ",".join(result)
        newFile  = "\n"
with open('some.csv', "w") as csv_file:
    csv_file.write(newFile)

CodePudding user response:

If you are using excel and python a lot, get familiar some Pandas tricks that help interfacing with excel. Here's a simple copy/paste approach.

  1. Copy the header of the excel document:
  2. Run the python code in a jupyter notebook:
import pandas as pd

df = pd.read_clipboard()
df.columns = [f'"{col}"' for col in df.columns
df.to_clipboard(index=False)
  1. Paste the updated columns into the excel file.
  • Related