I have a csv file with three lines and three columns here.
At first I want to print all the lines. Subsequently, for each of them, program check whether it is written in the second field(index 1) USA. If so, program will take the price from the third field and multiply it by two.
Now I need to rewrite this doubled price instead of 2000 (in line with the USA)
import csv
with open('countries.csv', 'r') as source:
reader = csv.reader(source)
writer = csv.writer(source)
for line in reader:
print(*line, sep=';')
with open('countries.csv', 'r') as source:
reader = csv.reader(source)
for line in reader:
if line[2] == "USA":
actual_price = int(line[2])
print(actual_price)
new_price = int(actual_price) * 2
print(new_price)
Someone has already advised me to use the creation of a new file. But this causes problems when I want to work with the data in the file first.
import csv
import os
with open('countries.csv', mode='r') as oldfile, open(
'countries.tmp', mode='w', newline='') as newfile:
# define a reader and a writer
reader = csv.reader(oldfile, delimiter=';', quotechar='"')
writer = csv.writer(newfile, delimiter=';', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
for line in reader:
print(*line, sep=';')
# copy everything changing the third field
for line in reader:
if line[2] == "USA":
actual_price = int(line[2])
print(actual_price)
new_price = int(actual_price) * 2
print(new_price)
for row in reader:
writer.writerow([row[0], row[1], ,new_price])
# ok, time to rename the file
os.replace('countries.tmp', 'countries.csv')
Thank you for answer
CodePudding user response:
You are changing new_price
at every iteration of your for
loop. You should therefore be writing the row within the loop where you change the value:
with open('countries.csv', mode='r') as oldfile, open('countries.tmp', mode='w', newline='') as newfile:
reader = csv.reader(oldfile, delimiter=';', quotechar='"')
writer = csv.writer(newfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in reader:
price = int(row[2])
if row[1] == "USA":
price = price*2
writer.writerow([row[0], row[1], price])
os.replace('countries.tmp', 'countries.csv')