使用 'to_csv' 和 'os.path' 将 CSV 保存在与 python 文件相同的目录中?
Save a CSV in same directory as python file, using 'to_csv' and 'os.path'?
我希望此行将 csv 与我的 python 文件一起保存在当前目录中:
df.to_csv(./"test.csv")
我的 python 文件在 "C:\Users\Micheal\Desktop\VisualStudioCodes\Q1"
不幸的是,它保存在 "C:\Users\Micheal" 中。
我已经尝试导入 os 路径以使用 os.curdir
但除了错误之外我什么也没得到。
有没有办法使用 os.curdir
将 csv 与 python 文件一起保存?
或者是否有更简单的方法可以在 python 中执行此操作而无需导入任何内容?
import os
directory_of_python_script = os.path.dirname(os.path.abspath(__file__))
df.to_csv(os.path.join(directory_of_python_script, "test.csv"))
如果您想稍后阅读相同的 .csv
文件,
pandas.read_csv(os.path.join(directory_of_python_script, "test.csv"))
这里,__file__
给出了正在运行的python脚本的相对位置(路径)。我们通过os.path.abspath()
获取绝对路径,然后将其转换为父目录的名称.
os.path.join()
将两个路径连接在一起,考虑到路径分隔符的操作系统默认值,例如 '\'
用于 Windows 和 '/'
用于 Linux。
这种方法应该可以,我没试过,如果不行,请告诉我。
我希望此行将 csv 与我的 python 文件一起保存在当前目录中:
df.to_csv(./"test.csv")
我的 python 文件在 "C:\Users\Micheal\Desktop\VisualStudioCodes\Q1"
不幸的是,它保存在 "C:\Users\Micheal" 中。
我已经尝试导入 os 路径以使用 os.curdir
但除了错误之外我什么也没得到。
有没有办法使用 os.curdir
将 csv 与 python 文件一起保存?
或者是否有更简单的方法可以在 python 中执行此操作而无需导入任何内容?
import os
directory_of_python_script = os.path.dirname(os.path.abspath(__file__))
df.to_csv(os.path.join(directory_of_python_script, "test.csv"))
如果您想稍后阅读相同的 .csv
文件,
pandas.read_csv(os.path.join(directory_of_python_script, "test.csv"))
这里,__file__
给出了正在运行的python脚本的相对位置(路径)。我们通过os.path.abspath()
获取绝对路径,然后将其转换为父目录的名称.
os.path.join()
将两个路径连接在一起,考虑到路径分隔符的操作系统默认值,例如 '\'
用于 Windows 和 '/'
用于 Linux。
这种方法应该可以,我没试过,如果不行,请告诉我。