'pandas to.csv method doubles all '\'
so i am trying to save a dataframe to csv using the pandas library for some reason the to_csv pandas method is changing the directory i am referring to...
A = ['1', '2', '3', '4', '5']
B = ['one', 'two', 'three', 'four', 'five']
df = percentile_list = pd.DataFrame(
{'lst1Title': A,
'lst2Title': B})
print(df)
ticker_name = "AAPL"
path = fr'C:\Users\my_name\Documents\python projects\my_project\{ticker_name}_stock-price.csv'
print(path)
df.to_csv(path)
it tells me that the directory does not exist... beyond that pycharm marks the "path" string in the to_csv line and says "Expected type 'None', got 'str' instead " while i know that the to_csv method can handle strings... any one?
first part was answered so i edited it out... any one can help with whats left?
Solution 1:[1]
The functionality of it adding a backslashes to your path is normal as it is resolving the path and is returning an escaped string.
Just adjust your path variable like so and try again:
path = fr'C:\Users\my_name\Documents\python projects\my_project\{ticker_name}_stock-price.csv'
Solution 2:[2]
Consider the OS agonstic file path concatenation to avoid path separator issues where every subfolder is specified in comma-separated elements with base file at the end.
import os
...
path = os.path.join(
"C:", "Users", "my_name", "Documents", "python projects",
"my_project", "f{ticker_name}_stock-price.csv"
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Richard |
| Solution 2 | Parfait |
