CSV file not printing? - python

Can anyone explain why this won't print anything?
import csv
def main():
with open('MaxWatt1.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row

You need to call the main function at the end of the program:
import csv
def main():
with open('MaxWatt1.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
main() # Call main function.
Python does not have a main function like C/C++ does (one which gets called implicitly when you run the program). Instead, Python treats the function you have defined as it would any other function. The name main is only significant to the humans reading your code (and maybe some code analysis tools).
Actually, it would probably be best to do:
import csv
def main():
with open('MaxWatt1.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
if __name__ == '__main__':
main()
This ensures that the main function is only called when you run the program directly. If you import your file however, the call to main will be skipped. For more information, see:
What does if __name__ == "__main__": do?

So to add to what iCodez said:
import csv
def main():
with open('MaxWatt1.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
main()
will work for you

Related

How to delete Row while printing into excel format

I have simple code written in python. while writing into an excel file. I found additional rows get added each time. How can I skip the empty row added each time. and print data one after the other in an excel file
import csv
from datetime import datetime
import time
filename = 'testformat.csv'
fields = ['SLNo', 'Date', 'Time', 'RData', 'BData', 'GData', 'IRData']
date_format = datetime.now().strftime('%Y/%m/%d')
current_time = datetime.now().strftime('%I:%M:%S,%f')
def main():
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
for i in range(30):
csvwriter.writerow([i, date_format, current_time])
if __name__ == '__main__':
main()
What you need is already here : https://stackoverflow.com/a/3191811/18081892
You have to use :
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:

Python Multithreading CSV Read Write Sort

I have a use case to read from a csv file (inputs.csv) and call an API endpoint for each row of the csv. And write the output into a different csv (outputs.csv) and sort the output csv by a particular column. I am able to achieve all that by the below code. Need to find out if I can do it more efficiently in a multi-threaded way.
def main():
start = time.time()
print "read from csv file "
input_file = 'inputs.csv'
output_file = 'outputs.csv'
read_write_csv(input_file, output_file)
print("after output-->",time.time() - start)
sort_csv(output_file)
print("after sort -->",time.time() - start)
def read_write_csv(input_file, output_file):
with open(input_file, 'r') as csv_file:
reader = csv.reader(csv_file)
# Reading row by row
count = 0
for row in reader:
# Opening csv result file in append mode
with open(output_file, "a+") as csv_save:
writer = csv.writer(csv_save)
print "mac address ", row[0]
writer.writerow([row[0], callExternalAPI(row[0])]),(row,))
print "{0} devices processed so far".format(count+1)
csv_save.close()
def sort_csv(output_file):
with open('sorted.csv', 'w') as csv_final:
r = csv.reader(open(output_file), delimiter=",")
writer_final = csv.writer(csv_final)
sortedResponse = sorted(r, key=operator.itemgetter(1), reverse=True)
for row in sortedResponse:
writer_final.writerow(row)
main()
As you can see, I am a python newbie here so any suggestion to improve the code is most welcome.

Write a result of a function in a csv

I'm trying to write the result of a function in a csv. Unfortunately, no pandas.
csv file input:
Hello all well?
today is cold!
I have not had lunch yet
He does not have many brothers or sisters.
We are sick
Script:
import re
import csv
import string
with open('teste_csv.csv', 'r') as f:
file = csv.reader(f)
for line in file:
message = ''.join(line)
def toto(message):
message = message.lower()
p = re.compile('|'.join(map(re.escape, string.punctuation)))
no_punct = p.sub(' ', message)
writer = csv.writer(open('result.csv', 'w'))
for row in no_punct:
writer.writerow(row)
return writer
print(toto(message))
At my terminal, I have <_csv.writer object at 0x7fee60e57c50> and in my result.csv I have only one line written 'w'. I would like each line to be in my result.csv
You keep erasing the file since everytime you call toto it opens result.csv for writing, hence you are left only with a single write. You need to open the file once ,and create the wirter once. You also only need to define the function once for that matter:
import re
import csv
import string
def toto(message,writer):
message = message.lower()
p = re.compile('|'.join(map(re.escape, string.punctuation)))
no_punct = p.sub(' ', message)
for row in no_punct:
writer.writerow(row)
with open('teste_csv.csv', 'r') as f:
writer = csv.writer(open('result.csv','w'))
file = csv.reader(f)
for line in file:
message = ''.join(line)
toto(message,writer)
You need to put the writer outside of your first loop. each time you are looping throw it's opening and rewriting the file
another issue you are defining and calling the toto inside the loop so it's getting called with last message value.
import re
import csv
import string
with open('test.csv', 'r') as f:
file = csv.reader(f)
writer = csv.writer(open('result.csv', 'w'))
def toto(message):
message = message.lower()
p = re.compile('|'.join(map(re.escape, string.punctuation)))
no_punct = p.sub(' ', message)
for row in no_punct:
writer.writerow(row)
return writer
for line in file:
print line
message=''.join(line)
print(toto(message))

Saving integers within pickle and calling them

So this is my code, I would like to save the value 'test' to the file so that it can be called to be used when the program is reopened.
import pickle
test = 0
def Save():
with open('objs.pickle', 'wb') as f:
pickle.dump(test, f)
def Load():
with open('objs.pickle', 'rb') as f:
test = pickle.load(f)
The problem with this code is that when I reopen the program and run in and then type in Load(), it says that 'test' is still equal to 0. (Missing somehting obvious probably)
And so my question is, how could I fix the problem issued in italics?
The global variable test has nothing to do with test inside the function Load(). Change your function to:
def Load():
with open('objs.pickle', 'rb') as f:
return pickle.load(f)
Now this function returns the value it reads from the pickle file.
Call it like this:
print(Load())
Side note: By convention functions names are all lowercase in Python. So the function name should be actually load().
EDIT
The whole program in a better style:
import pickle
def save(file_name, obj):
with open(file_name, 'wb') as fobj:
pickle.dump(obj, fobj)
def load(file_name):
with open(file_name, 'rb') as fobj:
return pickle.load(fobj)
def main():
test = 0
file_name = 'objs.pickle'
save(file_name, test)
print(load(file_name))
if __name__ == '__main__':
main()

Modifying script: NameError: name '' is not defined

I am having problems with modifying a code written by someone else. Basically, trying to get the script to read a list of inputs(gene names) but I'm getting the following error:
NameError: name 'gene_name' is not defined
Below is the code:
import csv
fullout = np.empty((1,3704))
def gene_list(gene_name):
gene_list = open('C:\Users\Work\Desktop\Book1.csv', 'rU'), f
gene_list = []
reader = csv.reader(f)
for row in reader:
gene_name = "row.strip()"
for gene_name in gene_list(gene_name):
if __name__ == '__main__':
with gene_list:
reader = csv.reader(f)
for row in reader:
gene_name = row
probes_dict = get_probes_from_genes(gene_name)
expression_values, well_ids, donor_names = get_expression_values_from_probe_ids_hdf(
probes_dict.keys())
print get_mni_coordinates_from_wells(well_ids)`
gene_name is defined inside the scope of the function, as remarked by Padraic Cunningham. Once the function is over, you can't use this variable anymore.
I recommend you to read the docs about scopes. Scopes and Namespaces

Categories