0

I was writing a python script which will take some data from sql server and then write to the current directory as excel. I am using pandas for it. And to get the current directory I am using package os

import os

def getCurrDir():
   return os.getcwd().replace(" ","\ ")

now when calling this function while writing a excel sheet like this

writer = pandas.ExcelWriter(str(self.getCurrDir())+"/Temp_ID.xlsx", engine="xlsxwriter")
temp.to_excel(writer,"Temp_ID_Data", index=False)
writer.save()

I am not able to write because the error is

FileNotFoundError: [Errno 2] No such file or directory: '/home/srinath/Documents/Copy/Affine/workspace\\ python/Swipe/Temp_ID.xlsx'

One can see that the double slash is coming up. I thought that double slash is just for representation and I have learnt from this link . So what is going on? I am using python 3.4 from continuum. I am using centos 7 64 bit.

Community
  • 1
  • 1
srinath29
  • 345
  • 2
  • 4
  • 14

2 Answers2

4

You don't need escape the spaces in Python.

Define getCurrDir() as

def getCurrDir():
   return os.getcwd()

When you escape your spaces in Python with a backslash, Python then thinks your intended path has a backslash in it, and tries to handle the file access by adding another backslash to your backslash. Hence the invalid workspace\\ python file access attempt.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
1

You can use os.path.join and os.getcwd to create correct path:

writer = pandas.ExcelWriter(os.path.join(os.getcwd(),"Temp_ID.xlsx"), engine="xlsxwriter")
Ali Nikneshan
  • 3,500
  • 27
  • 39