Export multiple print statements to csv using python 3.5 - python-3.5

I have csv file which have two columns and i want to export it into the format i want. SO far i am able to print it into shell, i am struck with exporting that into csv file. Below is the code so far I have tried.
import csv
with open('file.csv','r') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader)
sku = 0
with open('newfile.csv','w') as new_file:
csv_writer = csv.writer(new_file)
for i in csv_reader:
sku = sku + 1
csv_writer.writerow(i)
print("message:: {")
print(" Message ID :",sku)
print(" sku :", i)
Any help or pointer would be helpfull. Thank you

Related

Printing data from the csv file

I wanna ask how do I print the number of dentists respective in 2012 from the CSV file.
import csv
csv_file = open('project.csv' , 'r')
data_file = csv.reader(csv_file)
def opt_a():
next(data_file)
for row in data_file:
i = row[1:]
print(i)
opt_a()
This what I have tried but I will only be able to print out in rows.
Sample of data :
year,Private Dental Specialists,Private General Dental Practitioners,Public Dental Specialists,Public General Dental Practitioners
2008,116,864,47,268
2009,180,863,74,246
2010,185,874,87,267
2011,199,961,77,241
2012,203,1012,86,271
2013,219,1192,88,308
2014,216,1219,96,348
2015,215,1326,102,347
2016,219,1425,106,380
2017,232,1516,112,365
2018,189,1579,113,412
2019,237,1644,130,379
In your for loop, simply check if the first value of your row is 2012 :
import csv
csv_file = open('project.csv' , 'r')
data_file = csv.reader(csv_file)
def opt_a():
next(data_file)
for row in data_file:
if row[0] == "2012":
i = row[1:]
print(i)
opt_a()

How do I remove first column in csv file?

I have a CSV file where the first row in the first column is blank with some numbers in the second and third row. This whole column is useless and I need to remove it so I can convert the data into a JSON file. I just need to know how to remove the first column of data so I can parse it. Any help is greatly appreciated!
My script is as follows
#!/usr/bin/python3
import pandas as pd
import csv, json
xls = pd.ExcelFile(r'C:\Users\Andy-\Desktop\Lab2Data.xlsx')
df = xls.parse(sheetname="Sheet1", index_col=None, na_values=['NA'])
df.to_csv('file.csv')
file = open('file.csv', 'r')
lines = file.readlines()
file.close()
data = {}
with open('file.csv') as csvFile:
csvReader = csv.DictReader(csvFile)
for rows in csvReader:
id = rows['Id']
data[id] = rows
with open('Lab2.json', 'w') as jsonFile:
jsonFile.write(json.dumps(data, indent=4))
I don't know much about json files but this will remove the first column from your csv file.
with open ('new_file.csv', 'w') as out_file :
with open ('file.csv') as in_file :
for line in in_file :
test_string = line.strip ('\n').split (',')
out_file.write (','.join (test_string [1:]) + '\n')

How to import a specific Key with its values in a csv file using Python?

In my program, the user will enter a country name and my code will first whether or not the country name exists in the dictionary. If it exists, the code has to print the country name and its associated values in a csv file. However, I am unable to do the csv part. I have presented the dictionary and relevant code for this issue. Kindly let me know what the issue is.
import string
import re
import csv
data = {
"Pakistan": (0.57, 0.05, 0.79),
"India": (0.47, 0.12, 0.54),
"Bangladesh": (0.49, 0.17, 0.81)
}
csv_columns = ['Country Name','1997','1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010']
csv_file = "Emissions_subset.csv"
con_name = input("Write up to three comma-separated countries for which you want to extract data: ")
count = len(re.findall(r'\w+', con_name))
if count == 1:
con_check1 = con_name.split()[0]
if con_check1.lower() in map(str.lower, data.keys()):
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
writer.writerow(list(data.keys()).index(con_check1))
print("Data successfully extracted for countries {} saved into file Emissions_subset.csv".format(con_check1.capitalize()))

how to read data from csv to feed them to cnn?

I have the following csv structure:
image_id, class_name, color, browneyes, feature2, feature3, feature4
for example:
429759,dog,black,1,0,0,husky
352456,cat,white,0,0,0,any
how can i read the csv file so for each row it reads the image file and feeds it to the model? (the image_id is the image filename)
you haven't mentioned what language you code in your question, but since you've mentioned Python in question's tags I show you an example in python
in python there is a nice python built-in module named csv that you can use it for working with CSV files
see the code below
CSV sample
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
Code
import csv
with open('employee_birthday.txt') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1
else:
print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
line_count += 1
print(f'Processed {line_count} lines.')
reference : https://realpython.com/python-csv/
official docs : https://docs.python.org/3/library/csv.html

Saving list to a .csv file

I have made a code that opens a .csv file and takes a user input to filter it to a new list. What I am having trouble with is saving this new list to a .csv file properly.
This is my code:
#author: Joakim
from pprint import pprint
import csv
with open ('Change_in_Unemployment_2008-2014.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
next(readCSV) #Removing header
result = []
found = False
user_input = input("Please enter a full/partial NUTS code to filter by: ")
for row in readCSV:
if row[0].startswith(user_input):
result.append(row)
found = True
if found == False:
print("There are no registered NUTS codes containing your input.. Please try again")
if found == True:
print("\n Successfully found ", len(result), "entries!""\n")
pprint (result)
#store data in a new csv file
Stored_path = "C:\data_STORED.csv"
file = open(Stored_path, 'w')
writer = csv.writer(file)
writer.writerow(["NUTS CODE", " Municipality", " value"])
for i in range(len(result)):
new_row = result[i]
NUTS_CODE = new_row[0]
Municipality = new_row[1]
Value = new_row[2]
writer.writerow([NUTS_CODE, Municipality])
csvfile.close()
If one runs my code with an input of : PL, one gets this list:
[['PL11', 'odzkie', '2.2'],
['PL12', 'Mazowieckie', '1.2'],
['PL21', 'Maopolskie', '2.9'],
['PL22', 'Slaskie', '2'],
['PL31', 'Lubelskie', '1.1'],
['PL32', 'Podkarpackie', '5.8'],
['PL33', 'Swietokrzyskie', '2.6'],
['PL34', 'Podlaskie', '2.7'],
['PL41', 'Wielkopolskie', '1.6'],
['PL42', 'Zachodniopomorskie', '-1.1'],
['PL43', 'Lubuskie', '1.8'],
['PL51', 'Dolnoslaskie', '0'],
['PL52', 'Opolskie', '1.3'],
['PL61', 'Kujawsko-Pomorskie', '1.6'],
['PL62', 'Warminsko-Mazurskie', '2.4'],
['PL63', 'Pomorskie', '3.1']]'
Now I would like to store this neatly into a new .csv file, but when I use the code above, I only get a couple of values repeated throughout.
What is my error?

Resources