简体   繁体   English

使用“to_csv”和“os.path”将 CSV 保存在与 python 文件相同的目录中?

[英]Save a CSV in same directory as python file, using 'to_csv' and 'os.path'?

I want this line to save the csv in my current directory alongside my python file:我希望这一行将 csv 与我的 python 文件一起保存在我的当前目录中:

df.to_csv(./"test.csv")

My python file is in "C:\Users\Micheal\Desktop\VisualStudioCodes\Q1"我的 python 文件位于“C:\Users\Micheal\Desktop\VisualStudioCodes\Q1”

Unfortunately it saves it in "C:\Users\Micheal" instead.不幸的是,它将它保存在“C:\Users\Micheal”中。

I have tried import os path to use os.curdir but i get nothing but errors with that.我已经尝试导入 os 路径来使用os.curdir但我得到的只是错误。

Is there even a way to save the csv alongside the python file using os.curdir ?有没有办法使用os.curdir将 csv 与 python 文件一起保存?

Or is there a simpler way to just do this in python without importing anything?或者有没有更简单的方法可以在 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"))

And if you want to read same .csv file later,如果您想稍后阅读相同.csv文件,

pandas.read_csv(os.path.join(directory_of_python_script, "test.csv"))

Here, __file__ gives the relative location(path) of the python script being runned.在这里,__ __file__给出了正在运行的 python 脚本的相对位置(路径)。 We get the absolute path by os.path.abspath() and then convert it to the name of the parent directory .我们通过os.path.abspath()得到绝对路径,然后将其转换为父目录的名称。

os.path.join() joins two paths together considering the operating system defaults for path seperators, '\' for Windows and '/' for Linux, for example. os.path.join()将两条路径连接在一起,考虑到路径分隔符的操作系统默认值,例如, '\'用于 Windows 和'/'用于 Linux。

This kind of an approach should work, I haven't tried, if does not work, let me know.这种方法应该行得通,我没试过,如果行不通,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM