Python/Spyder : General Working Directory

标签 python python-3.x directory spyder

到目前为止,我的代码可以打开一个文本文件,将其操作为 pandas 数据文件,然后导出到 Excel。

我正在与其他人共享此代码,并且我们在 Spyder 中都有相同的工作目录。所有代码都工作正常,我想要操作的唯一行是文件的打开和文件的导出。

with open(r'C:\Users\"my_name"\Desktop\data\file.txt', 'r') as data_file:

这里的问题是,我想将工作目录设置为“\data”,以便我可以编写:

with open(r'file.txt', 'r') as data_file:

这样,我发送给其计算机上的工作目录也为“\data”的人就可以运行代码,并且它将选择其数据目录中的“file.txt”。

最佳答案

您在技术上寻找的答案是使用os.chdir(),如下所示

import os
os.chdir('.', 'data')
#THE REST OF THE CODE IS THE SAME
with open(r'file.txt', 'r') as data_file:

然而,更安全的答案是

def doTheThing(fName):
    return os.path.join(os.getcwd(),'data',fName)

with open(doTheThing('file.txt'), 'r') as data_file:

关于Python/Spyder : General Working Directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40140958/

相关文章:

python - 如何旋转 pandas 数据框?

java - 是否可以使用 JFileChooser 一次选择多个目录

file - grails:将文件上传到所选文件夹中

makefile - 如何获取当前文件夹的基本名称作为 makefile 中的变量?

python - Python 中列表函数的成本

python - 你可以使用 wxPython 自动隐藏框架/对话框吗?

python - 如果字符串单词包含特定字符,则删除包含该字符的单词

python - 向 django InlineFormSet 添加额外的字段

python - AppIndicator3.指示器: is there a way to hide/show it at runtime?

python-3.x - 无服务器框架 : Invoke local python function is slow to respond