I am trying to pass a many2one field to another database. Right now my program is using xmlrpc to get into a database and fetch data from a table called product.template and then creates a csv. The field that I want to pass returns
"[54, 'PARTS / COST']" along with the other fields. I only need the 54 which is the id. Any idea where to intercept this issue or how to solve it? this are the two methods that I got so far.
def FetchProducts(self):
products = self.odoo_object.execute_kw(
self.db,
self.uid,
self.password,
'product.template',
'search_read',
[[['sale_ok', '=', True], ['purchase_ok', '=', True]]],
{'fields': ['id', 'name', 'sale_ok', 'purchase_ok', 'type', 'default_code', 'barcode', 'list_price', 'standard_price', 'categ_id'], 'limit': 1}
)
return products
def ProductsCSV(self,products):
csv_columns = ['id', 'name', 'sale_ok', 'purchase_ok', 'type', 'default_code', 'barcode', 'list_price', 'standard_price', 'categ_id']
csv_file = "Products.csv"
try:
with open(csv_file, 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.DictWriter(csvfile, csv_columns, delimiter=',')
writer.writeheader()
for data in products:
writer.writerow(data)
print("Writing Products " + str(data))
except IOError:
print("I/O error")
I think you have problem in this line:-
--> with open(csv_file, 'w', encoding='utf-8', newline='') as csvfile:
so in my opinion please remove the arguments :- encoding and newline.
I run your code with project module it's perfectly worked.
Related
So I have these two functions in python:
import csv
#========== reader ==========#
def Test_reader(target_file):
with open(target_file, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter='\t')
for row in spamreader:
print(', '.join(row))
#========== DictReader ==========#
def Test_DictReader(target_file, dict_id):
# 'first_name' will be the dictionary's first row ID
fieldnames = ['first_name', 'last_name', 'email']
with open(target_file, "r", newline='') as csvfile:
spamreader = csv.DictReader(csvfile,fieldnames=fieldnames)
for row in spamreader:
print(row[dict_id])
print(Test_reader("names.csv"))
# Or
print(Test_DictReader("names.csv","first_name"))
There are no errors but it also prints "None"
Test_reader prints:
.....................................
.....................................
Corey,Smith,coreysmith#bogusemail.com
Mary,Patterson,marypatterson#bogusemail.com
Jane,Stuart,janestuart#bogusemail.com
Travis,Arnold,travisarnold#bogusemail.com
John,Robinson,johnrobinson#bogusemail.com
Travis,Arnold,travisarnold#bogusemail.com
None
Test_DictReader prints:
.....................................
.....................................
coreysmith#bogusemail.com
marypatterson#bogusemail.com
janestuart#bogusemail.com
travisarnold#bogusemail.com
johnrobinson#bogusemail.com
travisarnold#bogusemail.com
None
the csv file "names.csv" goes like this.
first_name,last_name,email
John,Doe,john-doe#bogusemail.com
Mary,Smith-Robinson,maryjacobs#bogusemail.com
Dave,Smith,davesmith#bogusemail.com
Jane,Stuart,janestuart#bogusemail.com
. . .
There are no spare spaces/lines.
I tried many ways/combinations to insert headers (I need to add two column headers) but the file doesn't accept headers at file creation. At best, I get headers as rows come into the file one after the other. I can't see how to enter the headers only once persistently. Can you see in the code below where I could make some change please? Thanks.
with open(MYFILE, "w", newline='') as csvWriter, open('read.csv', 'r', newline='') as csvReader:
if keyword != "q":
fieldnames = [engine, keyword]
#fieldnames = ['Engine', 'Keywords']
# writer = csv.DictWriter(csvWriter, fieldnames=[engine, keyword], extrasaction='ignore')
writer = csv.DictWriter(csvWriter, fieldnames=fieldnames)
writer.writeheader()
reader = csv.DictReader(csvReader, fieldnames=fieldnames)
writer.writerow({"Engine": engine, "Keywords": keyword})
writer.writerows(reader)
I'm trying to save data into a csv file. I have two columns but no headers currently. I'd need some column titles like in any spreadsheet basically.
UPDATE ==============================================
I've tried to insert to no avail the first block hereafter before and after the 2nd one. There is certainly something I'm not doing right but I don't know. Any suggestion, please?
STATUS = "quit"
print("Press [q] to quit at any time")
menu_engine = {}
menu_engine['1'] = "Google Search - Large Results"
menu_engine['2'] = "Google Search - Small Results"
menu_engine['3'] = "Yahoo Search - Large Results"
menu_engine['4'] = "Yahoo Search - Small Results"
while True:
options = menu_engine.keys()
for entry in options:
print(entry, menu_engine[entry])
engine = input("Enter your Type of Search: ")
while STATUS != "q":
keyword = input("Enter keyword(s): ")
with open(MYFILE, "a", newline='') as csvWriter:
if keyword != "q":
fieldnames = [engine, keyword]
writer = csv.DictWriter(csvWriter, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
THE EXPECTED OUTPUT in the CSV File:
Engine Number,Keywords
4,man man
4,mate mate
you write the header with writeheader() then you can just write the rows
import csv
with open('new.dat', "w", newline='') as csvWriter, open('test.dat', 'r', newline='') as csvReader:
fieldnames = ['Engine', 'Keywords']
writer = csv.DictWriter(csvWriter, fieldnames=fieldnames)
reader = csv.DictReader(csvReader, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(reader)
INPUT FILE
sef,56
sfd,67
eryt,67
sdfsf,34
OUTPUT FILE
Engine,Keywords
sef,56
sfd,67
eryt,67
sdfsf,34
UPDATE
I felt there should be an easier way to do this and seems you can use fileinput module from the standard python library to edit the same file inplace and insert the record at the start. this will save you having to the move or rename files.
import fileinput
headers = ['Engine','Type']
with fileinput.input('test.dat', inplace=1) as my_file:
for line in my_file:
if my_file.isfirstline():
print(",".join(headers))
print(line, end='')
Try:
df["new_column"]=" "
df.to_csv("your_file.csv", index= False)
print(df) #to see if it's what you need
I'm scraping data from an HTML table and want to bind multi-word headers together as a dictionary keys for the correct values.
How should I bind the correct headers?
How should I remove unwanted headers at the end?
with open(filename, 'w') as f:
for span in all_spans:
num_page_items = len(all_spans)
f.write(span.text)
driver.close()
with open(filename) as csvfile: # Reading csv file
csvreader = csv.DictReader(csvfile, delimiter=' ')
mydict = {}
for col in csvreader:
print(col)
I expect the output to look something like -
Symbol{'AIZ', ('Shares': 1520), ('Purchase Price': 106.31), ('Market Price': 111.59), ('Total Value': 169,616.80), ('Gain/Loss': 8,025.60), ('Gain/Loss %': 0.050%)}
If i use csv.DictReader I'm getting -
OrderedDict([('Symbol', 'AIZ'), ('Shares', '1520'), ('Purchase', '$106.31'), ('Price', '$8,025.60'), ('Market', '$169,616.80'), ('Total', '0.050%'), ('Value', 'Buy'), ('Gain/Loss', 'Sell'), ('%', None), ('Actions', None)])
And if I`ll use csv.reader I'm getting -
['AIZ', '1520', '$106.31', '$111.59', '$169,616.80', '$8,025.60', '0.050%', 'Buy', '|', 'Sell']
Output file
I am getting "raw" data from a csv file, and putting only what I need for a new csv file that will be used to auto add users to a different system...
I am unsure how to add the correct headers needed for the file.
I've tried looking at other examples of adding headers but have not figured this out yet...
The headers I need to add are as follows:
"ID Card Number","Name","E-Mail","User Level","Position","Status","Covered Under Insurance","Paid Insurance"
(and in that order)
import csv
def studentscsv():
with open('..\StudentEmails_and_StudentNumbers.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
with open('mydirectory\student_users.csv', mode='w', newline='') as output_file:
write = csv.writer(output_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)
for row in csv_reader:
a = row[0]
studentnumber = row[1]
firstname = row[2]
lastname = row[3]
grade = row[4]
studentname = firstname + " " + lastname
studentemail = firstname + "." + lastname + "#mydomain.org"
status = "Active"
position = "Student"
covered = "Yes"
paid = "Yes"
write.writerow([studentnumber, studentname, studentemail, grade, position, status, covered, paid])
def main():
"""
Controls the program execution
:param in_file: the name of the input file.
:return: None
"""
if __name__ == '__main__':
main()
The file generates fine with the way the code is written. I am just unsure what I need to change to add the headers.
Using the csv module, as you are, it's pretty straight forward. Define your headers in an array and then create a DictWriter with the fieldnames set to your array. Reference the following code and documentation:
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
Here's the documentation:
https://docs.python.org/2/library/csv.html#csv.DictWriter
I'm trying to print certain values into a CSV from a list I'm passing through. Here is my function:
current = datetime.datetime.now() #defining datetime for use in function
def write_csv(custody_parts):
with open((current.strftime("%m_%d_%y_%H_%M_%S")) + '.csv', 'w', newline='') as csvfile:
csvfile = io.StringIO()
fieldnames = ['serial', 'user', 'time']
writer = csv.DictWriter(csvfile, extrasaction='ignore', fieldnames=fieldnames)
writer.writeheader()
writer.writerows(custody_parts)
csvfile.getvalue()
print(csvfile.getvalue())
return(csvfile.getvalue())```
Then I call it with the list I'm trying to pass through:
write_csv(parts)
and it creates the file: 06_06_18_12_13_53.csv
and prints to the screen:
serial,user,time
serial1,user1,date1
serial2,user2,date2
serial3,user3,date3
but the file it creates is empty, so it isn't writing to the file it is creating.
Can someone point me in the right direction?
Thanks ~
EDIT:
I ended up going with this instead:
def write_csv(custody_parts):
current = datetime.datetime.now()
with open((current.strftime("%m_%d_%y_%H_%M_%S")) + '.csv', 'w', newline='') as csvfile:
custodywriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
custodywriter.writerow(['serial', 'user', 'time'])
for i in custody_parts:
x = [i["serial"],i["user"],i["time"]]
custodywriter.writerow(x)
custodywriter.writerow(["End of Report"])