当获取当前目录并用转义符和空格替换空格时

2024-10-03 21:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本,它将从sqlserver获取一些数据,然后以excel的形式写入当前目录。我用熊猫做的。为了得到当前的目录,我使用了package os

import os

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

当你在写excel表格的时候调用这个函数

^{pr2}$

我不能写,因为错误是

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

你可以看到双斜杠就要来了。我以为双斜杠只是用来表示的,我从这个link中学到了。怎么回事? 我使用的是continuum中的Python3.4。 我正在使用centos 7 64位。在


Tags: 数据import目录脚本packagereturnosdef
2条回答

您可以使用os.path.joinos.getcwd创建正确的路径:

writer = pandas.ExcelWriter(os.path.join(os.getcwd(),"Temp_ID.xlsx"), engine="xlsxwriter")

您不需要在Python中转义空格。在

getCurrDir()定义为

def getCurrDir():
   return os.getcwd()

当您用反斜杠转义Python中的空格时,Python会认为您的目标路径中有一个反斜杠,并尝试通过在反斜杠中添加一个反斜杠来处理文件访问。因此,workspace\\ python文件访问尝试无效。在

相关问题 更多 >