Store data in CSV file into an array? - python

If list stored in csv file below the example, does each row stored in the array?
import csv
import os
DIR = "C:/Users/Administrator/Desktop/key_list.csv"
def Customer_List(csv):
customer = open(DIR)
for line in customer:
row = []
(row['MEM_ID'],
row['MEM_SQ'],
row['X_AUTH_USER'],
row['X_AUTH_KEY'],
row['X_STORAGE_URL'])=line.split(",")
if csv == row['MEM_ID']:
customer.close()
return(row)
else:
print ("Not search for ID")
return([])
query = input("Input the your email id: ")
result = Customer_List(query)
This example alert errors code.. Why ..?
Additionally update the this code & error
Input the your email id: sdfsdf#naver.com
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\PyDev\Pydev\Day4\uCloudStorage.py", line 32, in <module>
result = Customer_List(query)
File "C:\Users\Administrator\Desktop\PyDev\Pydev\Day4\uCloudStorage.py", line 20, in Customer_List
row['X_STORAGE_URL'])=line.split(",")
ValueError: too many values to unpack (expected 5)
To show what's in the CSV, here's some simple code and the result:
DIR = "C:/Users/Administrator/Desktop/key_list.csv"
def Customer_List():
customer = open(DIR)
for line in customer:
print (line)
result:
MEM_ID, MEM_SQ, X_AUTH_USER, X_AUTH_KEY, X_STORAGE_URL
kimdm98#gmail.com, M100009, M100009:M100009, wreQew3u, AUTH_xxxxxx-xxxxx
minsejisuk#paran.com, M100022, M100022:M100022, PEm6tREx, AUTH_xxxxx-xxxxx
sdfsdf#naver.com, M100034, M100034:M100034, 3tAzEf3u, AUTH_xxxx-xxxxx
=============================================================================
I edited this script..... Is it best practice ?
DIR = "C:/Users/Administrator/Desktop/key_list.csv"
DATA = csv.reader(open(DIR,"r"))
ID = input("Input the Customer EMAIL ID: ")
def cList(value):
for row in DATA:
MEM_ID = row[0]
MEM_SQ = row[1]
X_AUTH_USER = row[2]
X_AUTH_KEY = row[3]
X_STORAGE_URL = row[4]
ACCESSKEY = row[5]
ACCESSKEYID1 = row[6]
SECRETKEY1 = row[7]
ACCESSKEYID2 = row[8]
SECRETKEY2 = row[9]
if MEM_ID == value:
print(".EMAIL ID :" + MEM_ID)
print(".MID :" + MEM_SQ)
print(".PASSWORD :" + X_AUTH_KEY)
print(".AUTH_ACCOUNT :" + X_STORAGE_URL)
print(".API KEY :" + ACCESSKEY)
cList(ID)
print ("============================")
print ("1. Upload / Download Error")
print ("2. Permission Error")
print ("3. 4xx Error")
print ("4. etc... Error")
print ("============================")
Result
Input the Customer EMAIL ID: kiyoung.jung#kt.com
.EMAIL ID :kiyoung.jung#kt.com
.MID :xxxxxx
.PASSWORD :xxxxxx
.AUTH_ACCOUNT :xxxxxx-d50a-xxxx-xxxbc05-6267d5ff6712
.API KEY :xxxxxxxx
============================
1. Upload / Download Error
2. Permission Error
3. 4xx Error
4. etc... Error
============================

If your input data is formatted like what you added at the very end of your question, your could get your approach to work like this:
import csv
DIR = "C:/Users/Administrator/Desktop/key_list.csv"
def Customer_List(email_id):
with open(DIR, newline='') as f: # open assuming Python 3.x
csvreader = csv.reader(f, skipinitialspace=True)
for fields in csvreader:
row = {} # initialize to an empty dictionary
(row['MEM_ID'],
row['MEM_SQ'],
row['X_AUTH_USER'],
row['X_AUTH_KEY'],
row['X_STORAGE_URL']) = fields
if row['MEM_ID'] == email_id:
return [row['MEM_ID'],
row['MEM_SQ'],
row['X_AUTH_USER'],
row['X_AUTH_KEY'],
row['X_STORAGE_URL']]
else:
print("ID not found")
return []
match = Customer_List('minsejisuk#paran.com')
if match:
print('found! {}'.format(match))
However you could simplify things slightly by using a csv.DictReader to read the file which will automatically read the header line to obtain the fieldnames and then return a dictionary using them as keys for each row read:
def Customer_List(email_id):
with open(DIR, newline='') as f: # open assuming Python 3.x
csvreader = csv.DictReader(f, skipinitialspace=True)
for row in csvreader:
if row['MEM_ID'] == email_id:
return [row['MEM_ID'],
row['MEM_SQ'],
row['X_AUTH_USER'],
row['X_AUTH_KEY'],
row['X_STORAGE_URL']]
else:
print("ID not found")
return []

Related

Writing columns to a CSV file

I would like to update a column called Score for a specific row in a csv file. When a button is pressed, I would like the code to search the csv file until the row with the specified name is found (which is stored in variable name and randomly pulled from the csv file in a previous function called NameGenerator()), and update the relevant cell in the Score column to increment by 1.
Please note I am using an excel file saved as a .csv for this.
Any ideas how to do this? The code below does not work. Any help would be appreciated.
def Correct():
writer = csv.writer(namelist_file)
score=0
for row in writer:
if row[0] == name:
score=score+1
writer.writerow([col[1]] = score)
![The CSV file looks as follows
]1
So for example if the name tom is selected (elsewhere in the code, however stored in variable name), his score of 3 should be incremented by 1, turning into 4.
Here is what the function which pulls a random name from the csv file looks like:
def NameGenerator():
namelist_file = open('StudentNames&Questions.csv')
reader = csv.reader(namelist_file)
rownum=0
global array
array=[]
for row in reader:
if row[0] != '':
array.append(row[0])
rownum=rownum+1
length = len(array)-1
i = random.randint(1,length)
name = array[i]
return name
Can you please check if this works :
import sys
import random,csv
def update(cells):
d=""
for cell in cells:
d=d + str(cell)+","
return d[:-1]
def update_score(name):
with open('StudentNames&Questions.csv', 'r') as file:
data = file.readlines()
name_index = - 1
score_index = -1
headers = data[0]
for index,header in enumerate(headers.split(",")):
if header.strip() == 'Names':
name_index=index
if header.strip() == 'Score':
score_index=index
if name_index == -1 or score_index == -1:
print "Headers not found"
sys.exit()
for index,row in enumerate(data):
cells = row.split(",")
if cells[name_index] == name:
cells[score_index] = int(cells[score_index]) + 1
data[index]=update(cells)
with open('/Users/kgautam/tmp/tempfile-47', 'w') as file:
file.writelines(data)
def NameGenerator():
namelist_file = open('StudentNames&Questions.csv')
reader = csv.reader(namelist_file)
rownum=0
global array
array=[]
for row in reader:
if row[0] != '':
array.append(row[0])
rownum=rownum+1
length = len(array)-1
i = random.randint(1,length)
name = array[i]
return name
randome_name=NameGenerator()
update_score(randome_name)

CSV not working if I put some extra space. Getting list index out of range error

I am new in python and I am trying to getting CSV data using python code.
Every thing is working first time,But when I edit my .csv file then an error occured says:
File "D:/wamp/www/optimizer_new/new_code/optimal_lineup.py", line 310, in get_player_list
if (int(row[4]) == -1):
IndexError: list index out of range
I am just putting a extra space inside my .csv
here is my sample code:
def get_player_list(possible_name):
file_name = ""
if (len(possible_name) > 0):
file_name = possible_name
else:
file_name = 'basketball_data2.csv'
player_list = []
with open(file_name) as csvfile:
reader = csv.reader(csvfile, delimiter=',')
reader.next()
for row in reader:
if (int(row[4]) == -1):
#print("Skipping %s" % (row[0]))
continue
name = row[0]
pos_p = get_possible_positions(row[1])
c = row[2]
v = row[3]
my_p = player(int(c) / 100, float(v), name, pos_p, int(row[4]))
player_list.append(my_p)
'''
name = row['Player Name']
c = row['Salary']
v = row['FP']
pos_p = get_possible_positions(row['Pos'])
player_list.append(player(c, v, name, pos_p))
'''
return player_list
My CSV contain these columns:
Player Name,Pos,Salary,FP,Keep/exclude
Any suggestion?

List input into dictionary

So I have a problem set for class where I am given a csv file of text abbreviations for words and I'm asked to prompt the user for multiple abbreviations and its supposed to return the full text if the abbreviation is found, if not then it will return the original abbreviation.
I'm currently stuck on getting the user input list into the dictionary properly.
import csv
def CreateDictionary(i):
abbrv = i.lower()
abbrv = i.split(' ')
dictionary = {}
fo = open('filename.csv')
data = csv.reader(fo)
for row in data:
dictionary[row[0]] = row[1]
fo.close()
def main():
user = input("abbreviations")
print(CreateDictionary(user))
main()
import csv
def CreateDictionary(i):
abbrv = i.lower()
abbrv = i.split(' ')
dictionary = {}
fo = open('filename.csv')
data = csv.reader(fo)
for row in data:
if row[0] in abbrv:
yield (row[0],row[1])
fo.close()
user = input("abbreviations")
print(list(CreateDictionary(user)))
might do what you are asking for
The csv library has a DictReader object you can use to automate the process.
https://docs.python.org/3/library/csv.html#csv.DictReader
Try adding the values of the keys in dictionary to a list if they are present
import csv
def CreateDictionary(i):
abbrv = i.lower()
abbrv = i.split(' ')
dictionary = {}
fo = open('filename.csv')
data = csv.reader(fo)
for row in data:
dictionary[row[0]] = row[1]
fo.close()
ret = []
for i in abbrv:
try:
ret.append(dictionary[i])
except KeyError:
ret.append(i)
return ret
def main():
user = input("abbreviations")
print(CreateDictionary(user))
main()

Unable to write list back to CSV

I am trying to write a code that takes in a csv, runs a ping on the value in the first column and then outputs the status to the second column. Everything in the code runs fine until it tries to write out to the csv at which time I get this error
line 35, in writer.writerows(columns)
TypeError: 'str' does not support the buffer interface
import os
import csv
from collections import defaultdict
i = 0
#read file
columns = defaultdict(list)
with open('hosts.csv') as f:
reader = csv.DictReader(f)
for row in reader:
for (k,v) in row.items():
columns[k].append(v)
f.close()
print('[DEBUG]', columns['host'])
print('[DEBUG] 1st host is', (columns['host'])[0])
print('[DEBUG]', columns['status'])
#ping hosts
hostname = (columns['host'])[i]
response = os.system("ping -n 1 " + hostname)
print ("[DEBUG]", response)
if response == 0:
print (hostname, 'is up')
(columns['status'])[i] = 'Up'
i = i+1
else:
print (hostname, 'is down')
(columns['status'])[i] = 'Down'
i = i+1
#write results
with open("hosts.csv", "wb") as f:
writer =csv.writer(f)
print("[DEBUG] just before write rows")
writer.writerows(columns)
print("[DEBUG] after write rows")
f.close()
The csv contains the following
host,status,name
8.8.8.8,down,google.com
and should return
host,status,name
8.8.8.8,Up,google.com
I am using Python 3.4
You are reading the CSV in one format and writing in another one, where columns is defaultdict with list of values inside a dict.
Here's a better way to solve this problem, maintaing the original file structure:
import os
import csv
with open('hosts.csv') as f:
reader = csv.DictReader(f)
rows = list(reader)
hosts = [row['host'] for row in rows]
statuses = [row['status'] for row in rows]
print('[DEBUG]', hosts)
print('[DEBUG] 1st host is', hosts[0])
print('[DEBUG]', statuses)
for row in rows:
#ping hosts
hostname = row['host']
response = os.system("ping -n 1 " + hostname)
print ("[DEBUG]", response)
if response == 0:
print (hostname, 'is up')
row['status'] = 'Up'
else:
print (hostname, 'is down')
row['status'] = 'Down'
#write results
with open("hosts.csv", "wb") as f:
writer = csv.DictWriter(f, reader.fieldnames)
# to maintain the same structure from the original file, rewrite header in original position
writer.writeheader()
print("[DEBUG] just before write rows")
writer.writerows(rows)
print("[DEBUG] after write rows")
Before instantiate csv.DictWriter, you can change the field names that you want to be in the new file:
newfieldnames = csvreader.fieldnames
lastfield = newfieldnames.pop() # remove last field
if 'field_name' in newfieldnames:
newfieldnames.remove('field_name') # remove by field name
writer = csv.DictWriter(f, newfieldnames)

Searching Python Dictionary by key value is returning multiple, consecutive results, not just 1

I am relatively new to Python and I am having trouble with the following.
I am trying to write a program that would read a CSV file of personal information and then display an individuals information based on entering an ID number.
It is almost working perfectly, except that when I search by id number, it is returning all of the results (rows) preceding the desired result, in addition to the result I want.
I am reading a CSV file into a dictionary. I am then naming the fields dynamically from the file based on the names from the CSV (theoretically the CSV file can contain 2 columns of data or 100, as long as there is one field named "id").
csvfile.txt looks like:
id,name,age
1,jay,35
2,jen,36
3,sam,38
4,mike,26
What I want is when I search for id "1", it returns:
"
id: 1
name: Jay
age: 35
"
...and it does.... but if I search for id "3", I am getting:
"
id: 1
name: Jay
age: 35
id: 2
name: Jen
age: 36
id: 3
name: Sam
age: 38
"
I can't figure out why it is not just returning the one row I am asking for... here is the core of the code:
def runprogram():
import csv
file = open(csvfile.txt, "r") #open my test file
reader = csv.DictReader(file, skipinitialspace=True, dialect='excel', delimiter=',')
totalfields = (len(reader.fieldnames)) #count all the fields in the files for the purpose of for looping.
result={} #new dictionary named result
resultfields = ""
i=1
for row in reader:
for i in range(1,totalfields):
resultfields = resultfields + reader.fieldnames[i] + ": " + row[reader.fieldnames[i]] + "\n"
i+1
result[row['id']] = resultfields #storing each line from the CSV into the results dictionary under the key "id"
#this was just some code so I could exit my program by typing "exit" in the input box...
idvalue=""
while idvalue != "exit":
#display the box in which to enter a id number
if idvalue =="":
message = "Enter id Number"
else:
message = result[idvalue]
#using easyGUI for my input and display boxes.
idvalue = eg.enterbox(msg=message,title='Print Results', default='', strip=True)
if idvalue:
identered = "1"#this was used for testing.
printresults(results[idvalue]) #call printresults function
else:
programmenu()
if idvalue =="exit":
exit()
def printresults(results):
output = "Information Requested:\n" + results
print(output)
Any help would be greatly appreciated!
You need to re-initialize resultfields for each row you process.
#!/usr/bin/python
import csv
def printresults(results):
print ("Information Requested:\n" + results)
file = open("/tmp/csvfile.txt", "r")
reader = csv.DictReader(file, skipinitialspace=True, dialect='excel', delimiter=',')
totalfields = (len(reader.fieldnames))
result={}
for row in reader:
resultfields = ""
for i in range(1,totalfields):
resultfields = resultfields + reader.fieldnames[i] + ": " + row[reader.fieldnames[i]] + "\n"
result[row['id']] = resultfields
idvalues = ["exit", "4"]
while 1:
idvalue = idvalues.pop() #eg.enterbox(msg=message,title='Print Results', default='', strip=True)
if idvalue == "":
message = "Enter id Number"
elif idvalue =="exit":
print "done"
exit()
else:
message = result[idvalue]
print(message)
Output now looks like:
name: mike
age: 26
done

Categories

Resources