How to save input data from terminal into a CSV file? - python

I'm trying to save input data from the terminal in a CSV file. Here is the code
import csv
field = ['Account', 'Name']
rows = []
filename = "db.csv"
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
csvwriter.writerow(field)
while True:
acc = int(input("Account No: "))
name = input("Enter Name: ")
rows[0] = acc
rows[1] = name
# writing the data rows
csvwriter.writerows(rows)
break
How to save those data in the CSV file?

rows is an empty list you can't use rows[0] and rows[1] like this.
You can use append() method
rows.append(acc)
rows.append(name)
csvwriter.writerows(rows)
or simply
csvwriter.writerows([acc, name])

This works for me:
import csv
field = ['Account', 'Name']
rows = []
filename = "db.csv"
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
csvwriter.writerow(field)
while True:
acc = int(input("Account No: "))
name = input("Enter Name: ")
# writing the data rows
csvwriter.writerow([acc, name])
keep_going = input("Continue? [y/n]")
if keep_going.lower() == "n":
break

Related

How to delete only one row from a CSV file with python?

I'm trying to make a program which stores a list of names in a CSV file, and I'm trying to add a function to delete rows, which isn't working as it deletes everything in the CSV file.
I've tried using writer.writerow(row), which hasn't worked.
memberName = input("Please enter a member's name to be deleted.")
imp = open('mycsv.csv' , 'rb')
out = open('mycsv.csv' , 'wb')
writer = csv.writer(out)
for row in csv.reader(imp):
if row == memberName:
writer.writerow(row)
imp.close()
out.close()
I expected the program to only delete rows which contained memberName, but it deletes every row in the CSV file.
How do I change it to only delete a single row?
You can't write to the same file while reading it. Instead, use another file for output, e.g.:
import csv
member_name = input("Please enter a member's name to be deleted: ")
with open('in_file.csv') as in_file, open('out_file.csv', 'w') as out_file:
reader = csv.reader(in_file)
writer = csv.writer(out_file)
for row in reader:
if member_name not in row: # exclude a specific row
writer.writerow(row)
Alternatively, you could store needed rows in memory and write them back to the input file after resetting the file pointer:
import csv
member_name = input("Please enter a member's name to be deleted: ")
with open('in_file.csv', 'r+') as in_file:
reader = csv.reader(in_file)
rows = [row for row in csv.reader(in_file) if member_name not in row]
in_file.seek(0)
in_file.truncate()
writer = csv.writer(in_file)
writer.writerows(rows)
This worked for me: you could write the contents of the csv file to a list, then edit the list in python, then write the list back to the csv file.
lines = list()
memberName = input("Please enter a member's name to be deleted.")
with open('mycsv.csv', 'r') as readFile:
reader = csv.reader(readFile)
for row in reader:
lines.append(row)
for field in row:
if field == memberName:
lines.remove(row)
with open('mycsv.csv', 'w') as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)

Continues columns in a csv-file with python

I have a Problem with continues writing my datas in a csv-file. I want a program that detects, if there is a csv-file for my measurements-data. If not it would be generated. When the csv-file is new generated the datas are written in the csv-file on the column after the header with the variable cycle = 0.
If the csv-file exists, the datas should be written continuously after the last line of the csv. Also the variable cycle should continue.
I have written a program that can detect if there is a file or not but with the continuously lines I have problems.
I hope someone can help me.
# mes = Array with 20 spaces filled with the Numbers 0-19
date = time.strftime("%d/%m/%Y")
def write(cycle, mes):
if os.path.exists('/home/pi/Documents/Ventilatorprüfstand_Programm/out.csv') is True: #does the out.csv existate?
print("Do something")
out = open('out.csv', 'w')
data = [[cycle, mes[0],mes[1],mes[2],mes[3],mes[4],mes[5],mes[6],mes[7],mes[8],mes[9],mes[10],mes[11],mes[12],mes[13],mes[14],mes[15],mes[16],mes[17],mes[18],mes[19], date]]
line = cycle+1
for row in data:
for line in row:
out.write('%s;' % line)
out.write('\n')
out.close()
else:
print("Do another something")
header = lookuptable.names()
out = open('out.csv', 'w')
for row in header:
for column in row:
out.write('%s' % column)
out.write('\t')
out.write('\n')
data = [[cycle, mes[0],mes[1],mes[2],mes[3],mes[4],mes[5],mes[6],mes[7],mes[8],mes[9],mes[10],mes[11],mes[12],mes[13],mes[14],mes[15],mes[16],mes[17],mes[18],mes[19], date]]
for row in data:
for column in row:
out.write('%s;' % column)
out.write('\n')
out.close()`
When opening the file with open() there is the option 'a' to append the new lines to the end:
'a' open for writing, appending to the end of the file if it exists
Here is an example using the csv Python standard library:
import csv
import os
import random
headers = ['cycle', 'date', 'speed', 'temp', 'power']
new_data = [[random.randint(0, 100) for _ in range(3)] for _ in range(2)]
date = '00/01/02'
cycle = 1
# Copy the data and include the date and the cycle number:
full_rows = [ [cycle, date, *row] for row in new_data ]
filename = 'example.csv'
# Check if the file exist, if not create the file with header
if not os.path.exists(filename):
print('creating a new file')
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerow(headers) # add the header
# Append the data to the file
with open(filename, 'a', newline='') as csvfile: # note the 'a' option
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerows(full_rows)

Python CSV Row Loop

I am very new to Python programming and decided on a small project to learn the language.
Basically I am trying to:
Read the first cell of a CSV file.
Ask if that cell value is "liked".
If liked, write to the column next to the cell on 1., "1".
Else, write "0".
Repeat on next row until end of list.
My code right now:
import csv
reader = csv.reader(open("mylist.csv"), delimiter=',')
data = []
for row in reader:
data.append(row)
ask = (data[0][0])
ans = input("Do you like {}? ".format(ask))
if ans == ("y"):
f = open('mylist.csv', 'r')
reader = csv.reader(f)
data = list(reader)
f.close()
data[0][1] = '1'
my_new_list = open('mylist.csv', 'w', newline='')
csv_writer = csv.writer(my_new_list)
csv_writer.writerows(data)
my_new_list.close()
else:
f = open('mylist.csv', 'r')
reader = csv.reader(f)
data = list(reader)
f.close()
data[0][1] = '0'
my_new_list = open('mylist.csv', 'w', newline='')
csv_writer = csv.writer(my_new_list)
csv_writer.writerows(data)
my_new_list.close()
So basically, I am stuck trying to get the content of the next row.
FYI, I am looking to implement machine learning to this process.
First learning how to do this in a basic manner.
Any help is welcome.
Thank you!
You shouldn't read from and write to the same file/list/dict at the same time. If you do, references to data may change. You can start with something like this for your task. However, note that as the file grows you code becomes slower.
import csv
reader = csv.reader(open("test.csv", 'r'), delimiter=',')
content = []
for row in reader:
item = row[0]
ans = raw_input("Do you like {}? ".format(item))
if ans == 'y':
content.append([item, 1])
else:
content.append([item, 0])
writer = csv.writer(open('test.csv', 'w'))
writer.writerows(content)
In my last work with csv I opened the file so:
import csv
with open(name) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
If you want the resultant csv file to contain all of the data from the input file but with the question results added in, you could use something like this.
It will insert you answer (0 or 1) after the first item in each record.
import csv
reader = csv.reader(open("mylist.csv", 'r'), delimiter=',')
data = []
for row in reader:
data.append(row)
for row in data:
ans = raw_input("Do you like {}? ".format(row[0]))
if ans == 'y':
row[1:1] = "1"
else:
row[1:1] = "0"
writer = csv.writer(open('myresult.csv', 'w'))
writer.writerows(data)

Writing specific value back to .csv, Python

I have a .csv file with some data that i would like to change.
It looks like this:
item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,r
item 2,411.21,3,r
item 3,40.0,1,r,c
My code runs most of what i need but i am unsure of how to write back on my .csv to produce this result
item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,x
item 2,411.21,3,r
item 3,40.0,1,r,c
My code:
print("Enter the item number:")
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for line in reader:
if line["item_required"] == 'r':
line_count += 1
if marked_item == line_count:
new_list = line
print(new_list)
for key, value in new_list.items():
if value == "r":
new_list['item_required'] = "x"
print(new_list)
with open("items.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(new_list.values())
There are several problems here
you're using a DictReader, which is good to read data, but not as good to read and write data as the original file, since dictionaries do not ensure column order (unless you don't care, but most of the time people don't want columns to be swapped). I just read the title, find the index of the column title, and use this index in the rest of the code (no dicts = faster)
when you write you append to the csv. You have to delete old contents, not append. And use newline='' or you get a lot of blank lines (python 3) or "wb" (python 2)
when you read, you need to store all values, not only the one you want to change, or you won't be able to write back all the data (since you're replacing the original file)
when you modify, you do overcomplex stuff I just replaced by a simple replace in list at the given index (after all you want to change r to x at a given row)
Here's the fixed code taking all aforementioned remarks into account
EDIT: added the feature you request after: add a c after x if not already there, extending the row if needed
import csv
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.reader(f, delimiter=',')
title = next(reader) # title
idx = title.index("item_required") # index of the column we target
lines=[]
for line in reader:
if line[idx] == 'r':
line_count += 1
if marked_item == line_count:
line[idx] = 'x'
# add 'c' after x (or replace if column exists)
if len(line)>idx+1: # check len
line[idx+1] = 'c'
else:
line.append('c')
lines.append(line)
with open("items.csv", 'w',newline='') as f:
writer = csv.writer(f,delimiter=',')
writer.writerow(title)
writer.writerows(lines)
Using pandas:
import pandas as pd
df = pd.read_csv("items.csv")
print("Enter the item number:")
marked_item = int(input())
df.set_value(marked_item - 1, 'item_required', 'x')
# This is the extra feature you required:
df.set_value(marked_item - 1, 'item_completed', 'c')
df.to_csv("items.csv", index = False)
Result when marked_item = 1:
item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,x,c
item 2,411.21,3,r,
item 3,40.0,1,r,c
Note that according to RFC4180 you should keep the trailing commas.
I guess this should do the trick:
Open a file which can read and written to update it (use "+r" for that)
instead of opening it again write it right there using csvfilewriter, which we create at the start.
file.py
import csv
fieldnames = ["item_name","item_cost","item_priority","item_required","item_completed"]
csvfile = open("items.csv", 'r+')
csvfilewriter = csv.DictWriter(csvfile, fieldnames=fieldnames,dialect='excel', delimiter=',')
csvfilewriter.writeheader()
print("Enter the item number:")
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for line in reader:
if line["item_required"] == 'r':
line_count += 1
if marked_item == line_count:
new_list = line
print(new_list)
for key, value in new_list.items():
if value == "r":
new_list['item_required'] = "x"
print(new_list)
csvfilewriter.writerow(new_list)
If you don't want to update the csv but want to write a new one, below is the code:
import csv
fieldnames = ["item_name","item_cost","item_priority","item_required","item_completed"]
csvfile = open("items_new.csv", 'w')
csvfilewriter = csv.DictWriter(csvfile, fieldnames=fieldnames,dialect='excel', delimiter=',')
csvfilewriter.writeheader()
print("Enter the item number:")
line_count = 0
marked_item = int(input())
with open("items.csv", 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for line in reader:
if line["item_required"] == 'r':
line_count += 1
if marked_item == line_count:
new_list = line
print(new_list)
for key, value in new_list.items():
if value == "r":
new_list['item_required'] = "x"
print(new_list)
csvfilewriter.writerow(new_list)
else:
csvfilewriter.writerow(line)

(Simple Python) CSV input to usernames

I have a CSV file names.csv
First_name, Last_name
Mike, Hughes
James, Tango
, Stoke
Jack,
....etc
What I want is to be able to take the first letter of the First_name and the full Last_name and output it on screen as usernames but not include the people with First_name and Last_name property's empty. I'm completely stuck any help would be greatly appreciated
import csv
ifile = open('names.csv', "rb")
reader = csv.reader(ifile)
rownum = 0
for row in reader:
if rownum == 0:
header = row
else:
colnum = 0
for col in row:
print '%-8s: %s' % (header[colnum], col)
colnum += 1
rownum += 1
ifile.close()
Attempt #2
import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile)
next(reader, None)
for row in reader:
if (row in reader )
print (row[0])
I haven't saved many attempts because none of them have worked :S
import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile, delimiter=',', quoting=csv.QUOTE_NONE)
for row in reader:
if not row[0] or not row[1]:
continue
print (row[0][0] + row[1]).lower()
Or
import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile, delimiter=',', quoting=csv.QUOTE_NONE)
[(row[0][0] + row[1]).lower() for row in reader if
row[0] and row[1]]
Once you get the text from the .csv you can use the split() function to break up the text by the new lines. Your sample text is a little inconsistent, but if I understand you question correctly you can say
import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile)
reader = reader.split('\n')
for x in reader
print(reader[x])
Or if you want to break it up by commas just replace the '\n' with ','
Maybe like this
from csv import DictReader
with open('names.csv') as f:
dw = DictReader(f, skipinitialspace=True)
fullnames = filter(lambda n: n['First_name'] and n['Last_name'], dw)
for f in fullnames:
print('{}{}'.format(f['First_name'][0], f['Last_name']))
You have headings in your csv so use a DictReader and just filter out those whose with empty first or last names and display the remaining names.

Categories

Resources