【问题标题】:How to save file to folder with the name of current Python script file?如何使用当前 Python 脚本文件的名称将文件保存到文件夹?
【发布时间】:2018-03-03 09:50:44
【问题描述】:

我有一个 Python 3 test.py 脚本,其中创建了一些数据,我想将这些数据保存到具有用户定义名称的文件中,例如 data.csv。该脚本所在的文件夹中有一个 /Results 文件夹。我想要做的是在Results 中使用当前脚本的名称创建一个子文件夹,并将我的文件存储在其中。所以,我想要的是将我的文件存储在./Results/test/data.csv 中。如果这些文件夹以前不存在,我希望创建这些文件夹,如果它们确实存在,连同文件,我希望 data.csv 被替换。我希望这适用于任何操作系统。这应该如何“以python方式”完成?

~/
  test.py
  Results/
     test/
        data.csv

这是一个测试代码,其中data.csv 没有保存在我想要的位置。我应该如何编辑它?

import pandas as pd

filename = "data.csv"
df = pd.DataFrame([1,2,3])
df.to_csv(filename)

【问题讨论】:

    标签: python-3.x path save


    【解决方案1】:

    您可以使用os.path 模块进行一系列文件夹检查,如果文件夹不存在,则创建该文件夹。然后你可以使用__file__属性访问当前文件名。

    import os.path
    import pandas as pd
    
    file_name = os.path.splitext(os.path.basename(os.path.realpath(__file__)))[0]
    
    full_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "Results")
    
    if not os.path.exists(full_path):
        os.mkdir(full_path)
    
        if not os.path.exists(os.path.join(full_path, file_name)):
            os.mkdir(os.path.join(full_path, file_name))
    
    file_location = os.path.join(full_path, file_name, 'data.csv')
    
    df = pd.DataFrame([1, 2, 3])
    df.to_csv(file_location)
    

    【讨论】:

      【解决方案2】:

      我会使用:

      import platform
      import os
      
      if platform.system().lower() == 'windows':
          print("%s" % os.path.expandvars("%USERPROFILE%"))
      elif platform.system().lower() == 'posix':
          print("%s" % os.path.expandvars("$PATH")) #or some other posix var like USER...
      else:
          print("What the heck type of os is this?!?")
      

      我认为this 也可能对你有用。

      【讨论】:

      • 我无法让它工作。你能检查我问题中添加的代码并告诉我它是如何完成的吗?
      • 抱歉,我是在学校电脑上使用的,所以无法测试。我现在就测试一下。
      猜你喜欢
      • 2020-06-29
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      相关资源
      最近更新 更多