I have this data and I want to replace the value of the pin with the given input using DictWriter
name,place,pin
john,usa,1234
corey,canada,1232
tom,usa,4534
def get_input(name,pin,place):
with open("data.csv",'a') as file:
data = csv.DictWriter(file,fieldnames=["name","place","pin"])
data.writerow({"name":name,"pin":pin,"place":place})
How I'm suppose to replace any value in this csv file
Here is an example how to read the data.csv
, change one pin
value and save the data using csv.DictReader
/ csv.DictWriter
:
import csv
# read the data as list of dicts
with open("data.csv", "r") as f_in:
reader = csv.DictReader(f_in)
data = list(reader)
# replace pin '1232' with '9999'
for row in data:
if row["pin"] == "1232":
row["pin"] = "9999"
# save the data
with open("output.csv", "w") as f_out:
writer = csv.DictWriter(f_out, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
The output.csv
becomes:
name,place,pin
john,usa,1234
corey,canada,9999
tom,usa,4534
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.