/anaconda3/lib/python3.5/zipfile.py error when attempting to write to an Excel file

patelbg2001
patelbg2001 used Ask the Experts™
on
Hi, I'm running a python script using Spyder (Python 3.5) on OSX 10.13.6 and keep on running into file not found errors when attempting to copy data into a Microsoft Excel file. It looks like a permissions issue, but I don't know how to resolve. Any help would be much appreciated,

import urllib.request
import pandas as pd
import sys
import os

sys.path.append('/Users/bhav\ 1/Documents/keepbak2/python')

from html_table_parser import HTMLTableParser

target = 'weblink'

#get website config
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')

#instantiate he parser and feed it
p = HTMLTableParser()
p.feed(xhtml)

#write the table into python list

cwd = os.getcwd()  # Get the current working directory (cwd)
print(cwd)

Table_List = p.tables

# Use the Pandas from_dict method to read the tables into
# a Pandas data frame

df = pd.DataFrame.from_dict(Table_List[0])

#CountryDied_Stats.to_excel('/Users/bhav\ 1/Documents/keepbak2/python/countrydiedtest.xlsx',
#                           na_rep='',
#                           float_format=None, columns=None,
#                           header=True, index=True,
#                           index_label=None, startrow=0,
#                           startcol=0, engine=None, merge_cells=True,
#                           encoding=None, inf_rep='inf', verbose=True)

#print(CountryDied_Stats)
#xlfile = 'countrydiedtest.xlsx'
xlfile = '/Users/bhav\ 1/Documents/keepbak2/python/countrydiedtest.xlsx '

cwd = os.getcwd()  # Get the current working directory (cwd)
files = os.listdir(cwd)  # Get all the files in that directory
print("Files in '%s': %s" % (cwd, files))

# open file for reading
fn = input(xlfile)
if os.path.exists(fn):
#    fh = open(fn, "r")
    print("row 56 open(fn, r)")
else:
#    fh = open(fn, "w")
    print(" row 59 open(fn, w)")

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(fn, engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Open in new window



runfile('/Users/bhav 1/Documents/keepbak2/python/html-table-parser/scrape1.py', wdir='/Users/bhav 1/Documents/keepbak2/python/html-table-parser')
Reloaded modules: html_table_parser.parser, html_table_parser
/Users/bhav 1/Documents/keepbak2/python/html-table-parser
Files in '/Users/bhav 1/Documents/keepbak2/python/html-table-parser': ['countrydiedtest.xlsx', 'LICENSE', 'README.md', 'scrape1.py', '.gitignore', '.python-version', 'html_table_parser', 'example_of_usage.py', 'html_table_converter']

/Users/bhav 1/Documents/keepbak2/python/countrydiedtest.xlsx
 row 59 open(fn, w)
Traceback (most recent call last):

  File "<ipython-input-3-e281686b8449>", line 1, in <module>
    runfile('/Users/bhav 1/Documents/keepbak2/python/html-table-parser/scrape1.py', wdir='/Users/bhav 1/Documents/keepbak2/python/html-table-parser')

  File "/anaconda3/lib/python3.5/site-packages/spyder_kernels/customize/spydercustomize.py", line 668, in runfile
    execfile(filename, namespace)

  File "/anaconda3/lib/python3.5/site-packages/spyder_kernels/customize/spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/bhav 1/Documents/keepbak2/python/html-table-parser/scrape1.py", line 73, in <module>
    writer.save()

  File "/anaconda3/lib/python3.5/site-packages/pandas/io/excel.py", line 1732, in save
    return self.book.close()

  File "/anaconda3/lib/python3.5/site-packages/xlsxwriter/workbook.py", line 306, in close
    self._store_workbook()

  File "/anaconda3/lib/python3.5/site-packages/xlsxwriter/workbook.py", line 635, in _store_workbook
    allowZip64=self.allow_zip64)

  File "/anaconda3/lib/python3.5/zipfile.py", line 1009, in __init__
    self.fp = io.open(file, filemode)

FileNotFoundError: [Errno 2] No such file or directory: ''
Screen-Shot-2018-08-28-at-22.59.16.png
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
My bet is on the space in the string "bhav\ 1" to be a problem.
Try duplicating backslash llike this: "bhav\\ 1" in the XLS string path.
python is not a shell. So normally you do not have to (must not) escape spaces.

you should use '/Users/bhav 1/Documents/keepbak2/python/countrydiedtest.xlsx'

but to quickly test what's wrong I suggest to run following code snippet:

import os

fname = '/Users/bhav 1/Documents/keepbak2/python/countrydiedtest.xlsx'
while True:
    parent_dir = os.path.dirname(fname)
    if fname == parent_dir:
        break
    if os.path.isdir(parent_dir):
        print("Directory %s exists" % parent_dir)
    else:
        print("Directory %s does not exist" % parent_dir)
    fname = parent_dir

Open in new window

changing the file path resolved my issue.

#xlfile = 'countrydiedtest.xlsx'
xlfile = "/Users/bhav 1/Documents/dump/countrydiedtest.xlsx"

Open in new window

Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

This is what I suggested in my answer:

python is not a shell. So normally you do not have to (must not) escape spaces.

you should use '/Users/bhav 1/Documents/keepbak2/python/countrydiedtest.xlsx'

So I'm a little surprised, that you accept your and not my solution

Author

Commented:
Agreed. It was my error. Thanks.
no problem. Happy coding

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial