简体   繁体   English

Python、Pandas、to_csv、os.path.join 参数格式

[英]Python, Pandas, to_csv, os.path.join argument formatting

I am trying to putput a dataframe to csv, and have noticed that the following code works:我正在尝试将数据框放入 csv,并注意到以下代码有效:

df.to_csv(os.path.join(string1, string2 + ".csv"))

However, on the other hand the following code does not work.但是,另一方面,以下代码不起作用。 Could someone kindly help me understand why?有人可以帮我理解为什么吗?

df.to_csv(os.path.join(string1, string2, ".csv"))

The two calls to os.path.join simply return different paths:os.path.join的两次调用只是返回不同的路径:

>>> import os.path
>>> string1, string2 = "X", "Y"
>>> os.path.join(string1, string2 + ".csv")
'X/Y.csv'
>>> os.path.join(string1, string2, ".csv")
'X/Y/.csv'

The latter will try to save a file called '.csv' in the subdirectory called 'Y' of the directory 'X' .后者将尝试在目录'X'的名为'Y'的子目录中保存一个名为'.csv'的文件。 The first code will try to save 'Y.csv' , which is a different file, stored in the 'X' directory.第一个代码将尝试保存'Y.csv' ,这是一个不同的文件,存储在'X'目录中。

The two lines give different file paths, so it makes sense that they can produce different behavior, since the in latter the 'Y' directory apparently doesn't exist.这两行给出了不同的文件路径,因此它们可以产生不同的行为是有道理的,因为后者中的'Y'目录显然不存在。


You can prevent future confusion by using the (somewhat, but not really) new pathlib standard module:您可以通过使用(有点,但不是真的)新的pathlib标准模块来防止将来出现混淆:

from pathlib import Path

df.to_csv(Path(string1) / f"{string2}.csv")

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

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