How to save an excel workbook from within python - python

I'm new to python I made this code which makes you input data that is Automatticly inputted into excel.
The thing is when I run the program twice it overwrites the previous data so I need to know how to save it.
this is the code I wrote
import xlsxwriter
workbook = xlsxwriter.Workbook('Book1.xlsx')
worksheet = workbook.add_worksheet()
name = input('your full name: ')
age = int(input('your age: '))
emaill = input('your email: ')
idontknow = (
['Name', name],
['Age', age],
['Email', emaill],
)
row = 0
col = 0
for item, cost in idontknow:
worksheet.write(row, col, item)
worksheet.write(row, col + 1, cost)
row += 1
workbook.close()
any suggestion will help

I would recommend using the pandas library to perform the data manipulation. A code that performs the task you indicate would be the following:
import pandas as pd
#read the file and make a DataFrame
data = pd.read_excel('Book1.xlsx')
df = pd.DataFrame(data)
#get the data
name = input('your full name: ')
age = int(input('your age: '))
email = input('your email: ')
#get the last edited row
row = len(df)
#write the data
df.loc[row, 'name'] = name
df.loc[row, 'age'] = age
df.loc[row, 'email'] = email
#save the file
df.to_excel('Book1.xlsx',index=False)
Additionally, this code allows you to have headers for each column in your file, which is convenient in most situations.

I would recommend using "csv" - https://docs.python.org/3/library/csv.html
excel can read and save to csv format, and I find it easier to work with.

openpyxl provide more functionality in parsing excel files, with similar syntax as xlsxwriter. (worksheet.max_row for example is accessible in openpyxl but not in xlsxwriter)
import openpyxl
workbook = openpyxl.load_workbook('Book1.xlsx')
worksheet = workbook.create_sheet(0)
name = input('your full name: ')
age = int(input('your age: '))
emaill = input('your email: ')
idontknow = (
['Name', name],
['Age', age],
['Email', emaill],
)
row = worksheet.max_row + 1
for item, cost in idontknow:
worksheet.cell(row=row, column=0, value=item)
worksheet.cell(row=row, column=1, value=cost)
row += 1
workbook.save('Book1.xlsx')

Related

I am trying to read excel file and its formulas and write them in new file by updating the formulas accordingly but got stuck to update them

I am trying to split excel spreadsheet based on columns and retain the formulas used in it. I was using openpyxl to read the formulas but got stuck as it reads formulas and write as it is but i need to modify them as well depending upon new splitted sheets.
My code is as :
enter code here
import pandas as pd
import os
from openpyxl import load_workbook
files = os.listdir("C:\\Users\\electrician\\Excel_Automation")
print("List of files: ")
for i in files:
print(i)
file_name = input("Enter the file name: ")
file = load_workbook(filename = file_name)
tabs = file.sheetnames
temp_dict1 = dict()
print("List of tabs: ")
for i,j in enumerate(tabs):
temp_dict1[i] = j
print(i,j)
tab_number = int(input("Enter tab number to split: "))
tab = pd.DataFrame(data=file[tabs[tab_number]].values)
temp_dict2 = dict()
print("List of columns: ")
for i,j in enumerate(tab[:1].values.tolist()[0]):
print(i,j)
column_number = int(input("Enter column number to split: "))
for i in set(tab[column_number]):
output_filename = temp_dict1[tab_number+1]+"_"+i+".xlsx"
df = tab[tab[column_number] == i].reset_index()
writer = pd.ExcelWriter("C:\\Users\\electrician\\Excel_Automation\\Output\\" + output_filename,engine='xlsxwriter')
for j in temp_dict1.values():
if j == temp_dict1[tab_number]:
df.to_excel(writer, sheet_name=output_filename, index=False)
else:
d = pd.DataFrame(data=file[j].values)
d.to_excel(writer,sheet_name=j,index=False)
writer.save()

to_csv storing columns label on every insert of data to csv file

when i am inserting data first time in csv file it is good
but on second time it again inserts column name
import pandas as pd
name = input("Enter student name")
print("")
print("enter marks info below")
print("")
eng= input("enter English mark : ")
maths= input("enter Maths mark : ")
physics= input("enter Physics mark : ")
chemistry= input("enter Chemistry mark : ")
ip= input("enter Informatic Practices mark : ")
dict = {
"name":{name:name},
"english":{name:eng},
"maths":{name:maths},
"physics":{name:physics},
"chemistry":{name:chemistry},
"ip":{name:ip}
}
df= pd.DataFrame(dict)
df.to_csv("hello.csv", sep="|",index=False,na_rep="null",mode='a')
print("hello.csv")
read = pd.read_csv("hello.csv", sep='|')
print(read)
data in csv file :
name|english|maths|physics|chemistry|ip
dddd|dd|e3|3|3|3
name|english|maths|physics|chemistry|ip
ddddddd|e33|33|3||3
name|english|maths|physics|chemistry|ip
dddddd|33|333||3|
please help in solving how to fix so that column not get added multiple time
you can read the csv file everytime before your run this script.
import pandas as pd
import os
df = pd.DataFrame() if not os.path.exists("hello.csv") else pd.read_csv("hello.csv", sep='|')
name = input("Enter student name")
print("")
print("enter marks info below")
print("")
eng = input("enter English mark : ")
maths = input("enter Maths mark : ")
physics = input("enter Physics mark : ")
chemistry = input("enter Chemistry mark : ")
ip = input("enter Informatic Practices mark : ")
dict = {
"name": {name: name},
"english": {name: eng},
"maths": {name: maths},
"physics": {name: physics},
"chemistry": {name: chemistry},
"ip": {name: ip}
}
df = df.append(pd.DataFrame(dict))
df.to_csv("hello.csv", sep="|", index=False, na_rep="null", mode='w')
print("hello.csv")
read = pd.read_csv("hello.csv", sep='|')
print(read)
and you can also use this code below to export df without columns, but may still have to check file existence or columns sequence first.
df.to_csv('filename.csv', header=False, sep='|', mode='a')
The output file is being opened in append mode, and to_csv() will include the header row by default. You could simply turn off the header:
df.to_csv("hello.csv", header=False, sep="|", index=False, na_rep="null", mode='a')
which will work, but your CSV file will not have a header row. If you require the header then you could check whether the output CSV file already exists and disable headers if it does.
One way is that suggested in the answer by #Eason, however, that might not be practical for large files due to the extra loading time (possibly this is the reason why you are using append mode?)
The following disables the CSV headers if the file already exists and is not empty.
from pathlib import Path
header = True
p = Path('hello.csv')
if p.exists() and p.stat().st_size:
header = False
df.to_csv(p, header=header, sep="|", index=False, na_rep="null", mode='a')

Printing whole row from excel with pandas or something else?

Hello i need some help i try to do this abouth 2hours i was looking on internet but i couldnt find any solution,
i want from excel to print horizontal row from name that i found
here is picture what i want to print https://imgur.com/a/lZduGCV
elif "name " in data:
baza = pd.read_excel('Baza.xlsx')
data = data.split(" ")
name = data[1]
botgovor("Hold a second.I will check data base for that name")
for name in baza:
botgovor("We have that name in database,What would you like to do with it?")
data = covekgovor()
robot(data)
if "check it" in data:
informacije = pd.read_excel('Baza.xlsx')
botgovor(informacije)
import xlrd
loc = ("excel_file.xlsx") # excel file name
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
search_name = "Landon"
for i in range(sheet.nrows):
if search_name == sheet.cell_value(i, 0):
print(sheet.row_values(i))

Transfering specific rows from one cvs file to another cvs file

So, I'm trying to transfer rows[0,1,2,9,10] from what I've designated as "e_file" to "no_file"
When I print "data" I am given the exact information I want, I was just wondering how I should proceed with transferring this data to a corresponding CSV file?
Thank you.
e_file = '/Users/massive/Desktop//NO/hour.csv'
no_file = '/Users/massive/Desktop/NO/combined.csv'
with open(e_file,'r') as e_r:
state_code = input("Enter state code: ")
county_code = input("Enter county code: ")
station_number = input("Enter station number: ")
csv_reader_2 = csv.reader(e_r)
for row in csv_reader_2:
if row[0] == str(state_code).zfill(2) and row[1] ==str(county_code).zfill(3) and row[2] == str(station_number).zfill(4):
data = [row[0],row[1],row[2],row[9],row[10]]
print(data)
Maybe something like (I cannot test it unless you provide a working example):
with open(newFile, 'wb') as csvfile:
fwriter = csv.writer(csvfile)
for line in data:
fwriter.writerow(line)

Could not append a csv file with dataframe rows

I am new to coding and learning python. I have been trying to create a program which asks user information about a part and then appends it to a file. Once it appends the file, I should be able to see the information in the file if i open it. However, the program is not saving the information on file. I might be doing a silly mistake but I have not been able to figure out as I am totally new to coding.
import sys
import pandas as pd
colnames = ['name', 'numid', 'length', 'height']
parts_info = pd.read_csv('part.info', sep ='\t', header = None, names = colnames, index_col = 'name')
New_parts = {}
class Part:
name = ""
numid = 0
height = 0
length = 0
def display(self):
print ''
print 'Part Information:'
print parts_info
def get(self):
self.name = raw_input('Enter Part Name: ')
self.numid = int(raw_input('Enter NumId: '))
self.height = float(raw_input('Enter Height (in feet): '))
self.length = int(raw_input('Enter Length: '))
def new_part(self):
New_parts[self.name] = {'numid':self.numid, 'height':self.height, 'length':self.length}
def save(self):
with open('part.info','a') as f:
parts_info.to_csv(f, header = False)
f.close()
onePart = None
if len(sys.argv) > 1 and sys.argv[1] == 'READ':
onePart = Part()
else:
onePart = Part()
onePart.get()
onePart.new_part()
onePart.save()
New_df = pd.DataFrame.from_dict(New_parts,orient='index')
New_df.index.name = 'name'
parts_info = parts_info.append(New_df)
onePart.display()
Code corrections and Commentary
There are a couple things:
You do not need to define the column names, when using pd.read_csv, they will be inferred from the csv based on the default header= argument. Also index_col= should be an int. You can read in with
parts_info = pd.read_csv('part.info', sep ='\t', index_col=0)
When .save() is called no data has been appended to the DataFrame yet. Put some print statements in so you can see the flow, like
def save(self):
print 'saving', parts_info
with open('part.info','a') as f:
parts_info.to_csv(f, header = False)
or
print 'make new part'
onePart = Part()
print 'get new part info'
onePart.get()
print 'add to log'
onePart.new_part()
print 'save it to csv'
onePart.save()
You need to restructure your code so things happen in the order you want them to.
When you use
with open('/path/to/file', 'a') as f:
you do not need
f.close()
See the best practice behind the with statement.

Categories

Resources