Ad
Write On A Csv Column And Change Header
i'm trying to use python to make a script that change a csv, i have to ask for an input that will be the same for all the lines and also have to change an header name but not all the values listed, here is the script
import csv
location= input("File Path: ")
with open(location) as csv_file:
csv_reader = csv.DictReader(csv_file)
with open('fixed.csv', 'w', newline='') as new_file:
fieldnames = "value", "type", "description"
writer=csv.writer(new_file)
csv_writer =csv.DictWriter(new_file, fieldnames=fieldnames, delimiter= '|', extrasaction='ignore')
csv_writer.writeheader()
for line in csv_reader:
line = {k: v.replace("sha1", "hash") for k, v in line.items()}
if not any("url" in value for value in line.values()):
csv_writer.writerow(line)
Here is the code, i have to change "value" header to a new word, and list under "description" the same thing that is asked to the user
sample of csv
value|type|description
35|new|
46|new|
54|new|
Ad
Answer
For the csv writer you need to declare the column names like so.
fieldnames = "new_column_name", "type", "description"
If you are Using python 3.7+ replace this line
line = {k: v.replace("sha1", "hash") for k, v in line.items()}
with
line = {"new_column_name" if k == 'value' else k:v.replace("sha1", "hash") for k,v in line.items()}
Otherwise, the following will work for any version. place this code after initializing the line variable
line = {'new_columne_name' : line['value'], 'type': line['type'], 'description' : line['description']}
if you want to change the value of the description at a certain line simply use this
line['description'] = new_value
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad