xlwings can not locate my file? - xlwings

I'm using python to operate a excel file.My python project is located at
D:\Python\Project
the excel file I wanna operate is located at
‪C:\Users\wenbo\Desktop\test.xlsx
Below is my code:
import xlwings
workbook=xlwings.Book(r"‪C:\Users\wenbo\Desktop\test.xlsx")
sheet = workbook.sheets['Sheet1']
sheet.cells(1, 1).value=1
When I run the code,there was an error:
FileNotFoundError: No such file: '‪c:\users\wenbo\desktop\test.xlsx'
This is not right,I'm sure test.xlsx is located on my desktop.
But when I move test.xlsx to
D:\Python\Project
the following code works fine:
import xlwings
workbook=xlwings.Book(r"test.xlsx")
sheet = workbook.sheets['Sheet1']
sheet.cells(1, 1).value=1
So,it seems that xlwings can only locate file in the same project folder.But I think there must be another way to locate a file wherever the file is,right?Can anyone give me some advice?Thanks!

The path works if you use single quote marks rather than double quote marks (at least when I test it your code doesn't work with the double quotes and does with single quotes).
import xlwings
workbook=xlwings.Book('C:\\Users\\[username]\\Desktop\\test.xlsx')
sheet = workbook.sheets['Sheet1']
sheet.cells(1, 1).value=1
The above code runs without throwing an exception on my machine. (As does using a raw string instead of the double backslash)

Related

Problem reading file with pandas uploaded to a django view

I'm uploading some excel and csv files to a django view using axios, then i pass those files to a function that uses pandas read_csv and read_excel functions to process them, the first problem i had was with some excel files that had some non utf-8 characters that pandas was unable to read, the only solution i found was to set "engine = 'python'" when reading the file (changing the encoding to utf-8-sig or utf-16 didn't work).
This works when i'm testing the script from my terminal, but when i use the same script on a view i get the following error: ValueError("The 'python' engine cannot iterate through this file buffer.")
This is the code i'm using:
try:
data = pandas.read_csv(request.FILES['file'], engine="python")
except:
print("Oops!",sys.exc_info(),"occured.")
trying the same function through the terminal works fine
pandas.read_csv("file.csv", engine="python")

add macro to excel using python xlswriter with data in original excel

I'm using the following code to add a Macro to Excel. I notice that the data / other WorkSheets from the original Excel had dropped completely but the Macro is showing.
This is the code that I am using:
import xlsxwriter
workbooks = xlsxwriter.Workbook('C:\\Users\\user\Desktop\\test.xlsm')
workbooks.add_vba_project('C:\\Users\\user\\Desktop\\vbaProject.bin')
workbooks.close()
I used the link http://xlsxwriter.readthedocs.io/example_macros.html and it seems to be the same from another page https://redoakstrategic.com/pythonexcelmacro/
I wondered if there is another library that I should use for this?
I tried the following link Use Python to Inject Macros into Spreadsheets it seems that here again the data from the original file is overwritten. Not sure if this is a duplicate or not, or if I missed something rather obvious ?
Thanks
Unfortunately, xlsxwriter can't load information from already existing Excel workbooks; it is only used for making new ones. You are overwriting your old workbook with a blank one that has your macros.
If you need to load information, look into openpyxl. It can be used for creating .xlsm files.
One way around it is to create the macro you want in another Excel so we can execute it to affect the other Excel. Then using win32.com it runs the VBA.
enter code here
#import win32com.client
#xl=win32com.client.Dispatch("Excel.Application")
#xl.Workbooks.Open(Filename="C:\\macro.xlsm",ReadOnly=1)
#xl.Application.Run("macro")
#xl = 0

I'm using Python to load data points using genfromtxt command but getting error message "data.txt not found"

I've saved a .txt file of data points onto my desktop. I wrote my script in spyder as follows:
from pylab import *
data = genfromtxt('data.txt', skip_header = 5, skip_footer = 6)
print data
This returns an error code saying "data.txt not found"
I've spent over 30 min trying to figure this out and I'm sure it's going to be a trivial fix. What am I missing?
With a "file not found" type of error, the error is likely based on a failed directory search, not with any specific modules like pylab. In your case, you can just add data.txt to the same directory as your script. This makes a relative search work. You can also specify the absolute path, like r'C:\users\<username>\desktop\data.txt'. Python does other things in a directory search, like looking at your PATH environment variable in Windows, but working with the relative and absolute paths are the easiest.

Can't save figure as .eps [gswin32c is not recognized]

I'm using Enthought Canopy with PyLab(64-bit). For my report I need to use Latex (XeLaTex) and the plots are done with matplotlib.
To have an first idea I just copied the second example from http://matplotlib.org/users/usetex.html and compiled it. It looks fine and I can save it as a normal png without problems. However if i try to save it as .eps or.ps it does not work and an error appears:
invalid literal for int() with base 10: "
Additionaly in the Pylab shell it shows:
'gswin32c' is not recognized as an internal or external command, operable program or batch file'.
If I save it as .pdf I have no problems except the text is all black instead of being red and blue. This is a problem because in my plots I have two axes and I need them colorized for better readability.
If I then try to delete some lines from the example given (all text) I still cannot save it as .eps nor .ps. I can't figure out the problem and all the other topics related to this have not given me an insight. So I really need your help because I can't use .png for my report.
Thank you in advance!!!
I finally managed to solve this problem. It might look weird but maybe other people can benefit from it.
The solution might depend upon the software you use. I use Enthought Canopy (Python) and MikTeX 2.9 under W8 64bit.
If you want to output .ps and .eps files with matplotlib using the 'text.usetex': True option then you will encounter the problem posted above.
Solution:
Download and install Ghostscript (32bit) from http://www.ghostscript.com/download/gsdnld.html.
Download ps2eps-1.68.zip from http://www.tm.uka.de/~bless/ps2eps. The proceeding is given in the manual, however I like to point out the part with the environment variables. In this last step you need to go to Control Panel --> System --> Advanced system settings. Then click on the header 'Advanced' and on the bottom of the window you see 'Environment Variables' on which you click. Then you use the 'New'-Button for User Variables for USERNAME. Then you type in as variable name 'ps2eps' and for variable value you type in the actual path where you have saved the ps2eps.pl file. In my case this is 'C:\Program Files (x86)\ps2eps\bin\'. You can check if you type 'ps2eps' in the command-window.
Download xpdfbin-win-3.03.zip from http://www.foolabs.com/xpdf/download.html. You only need the file 'pdftops.exe'. However I could not assign a path like in step 2. I solved this by putting the 'pdftops.exe' in the MikTeX 2.9 folder. The exact location for me was 'C:\Program Files\MiKTeX 2.9\miktex\bin\x64'.
I was then able to save figures as .ps and have no more any error messages. Remember to use the settings proposed on http://matplotlib.org/users/usetex.html under 'postscript options'.
In myself used the following settings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.rc('font', **{'family':'serif', 'serif':['Computer Modern Roman'],
'monospace':['Computer Modern Typewriter']})
params = {'backend': 'ps',
'text.latex.preamble': [r"\usepackage{upgreek}",
r"\usepackage{siunitx}",
r"\usepackage{amsmath}",
r"\usepackage{amstext}",],
'axes.labelsize': 18,
#'axes.linewidth': 1,
#'text.fontsize':17,
'legend.fontsize': 10,
'xtick.labelsize': 13,
#'xtick.major.width' : 0.75,
'ytick.labelsize': 13,
'figure.figsize': [8.8,6.8],
#'figure.dpi': 120,
'text.usetex': True,
'axes.unicode_minus': True,
'ps.usedistiller' : 'xpdf'}
mpl.rcParams.update(params)
mpl.rcParams.update({'figure.autolayout':True})
(whereas many of the params are just for my own purpose later in the plots)
As a beginner I am not well informed about the dependence from the 'backend' used if you are running a script from your python console. I however used this without any --pylab settings in before and I do not know if one needs to switch the backend manually if he is working already in a console with a specific matplotlib backend.
I had the same problem and my problem was a font adjustment in the python code that is :
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
when I remove this iit works fine and now i can save eps.
So be sure that any shortest working example is working for you or not then check the font and other style edits in your code. This may help.

How can I programmatically generate PDFs using LaTeX?

I'm trying to generate some LaTeX code which from thereon should generate PDF documents.
Currently, I'm using the Django templating system for dynamically creating the code, but I have no idea on as how to move on from here. I understand that I could save the code in a .tex file, and use subprocess to run pdflatex for generating the PDF. But I had so much trouble escaping the LaTeX code in "plain" Python that I decided to use the Django templating system. Is there a way that I could somehow maybe pipe the output produced by Django to pdflatex? The code produced is working properly, it's just that I do not know what to do with it.
Thanks in advance
I was tackling the same issue in a project I had previously worked on, and instead of piping the output, I created temporary files in a temporary folder, since I was worried about handling the intermediate files LaTeX produces. This is the code I used (note that it's a few years old, from when I was still new to Python/Django; I'm sure I could come up with something better if I was writing this today, but this definitely worked for me):
import os
from subprocess import call
from tempfile import mkdtemp, mkstemp
from django.template.loader import render_to_string
# In a temporary folder, make a temporary file
tmp_folder = mkdtemp()
os.chdir(tmp_folder)
texfile, texfilename = mkstemp(dir=tmp_folder)
# Pass the TeX template through Django templating engine and into the temp file
os.write(texfile, render_to_string('tex/base.tex', {'var': 'whatever'}))
os.close(texfile)
# Compile the TeX file with PDFLaTeX
call(['pdflatex', texfilename])
# Move resulting PDF to a more permanent location
os.rename(texfilename + '.pdf', dest_folder)
# Remove intermediate files
os.remove(texfilename)
os.remove(texfilename + '.aux')
os.remove(texfilename + '.log')
os.rmdir(tmp_folder)
return os.path.join(dest_folder, texfilename + '.pdf')
The dest_folder variable is usually set to somewhere in the media directory, so that the PDF can then be served statically. The value returned is the path to the file on disk. The logic of what its URL would be is handled by whatever function sets the dest_folder.