Search code examples
pythondataframefilepath

Python Data frame to CSV - Converting to Windows Filepath


The following code works for me on the MAC OS but I'm having trouble converting it to a windows file path. If I just make the forward slashes into back slashes the file turns to color red as if it is a literal.

dict=pd.DataFrame(elements_count, index=[0,])

dict.to_csv(path+'/Word_freq/'file+'.csv')

Thank you in advance for any help.


Solution

  • You can use os.path.join

    import os
    fullPath = os.path.join(path,'Word_freq', file + '.csv')
    

    In fact, I'd always prefer os.path.join over string concatenation, cause it will join the path based on the platform But if you still want to use string concatenation, then you can join the path, directory, subdirectory, or file name using separting them by by os.sep Like this:

    fullPath = path + os.sep + 'Word_freq' + os.sep + file + '.csv'