My project has a bunch of csv files that may or may not be called based on user input. I’d like to store these files in a subdirectory to keep my project folder uncluttered. I’m utterly confused as to how to do this. Most of the resources I’ve dug up involve importing a module or package from a subdirectory rather than a basic data file.
The line of code that imports my csv currently looks like:
target_doc = csv.reader(open('sample.csv', 'rU'), delimiter=",", quotechar='|')
I’m assuming a solution will involve setting up a path variable, using import os and import sys, and perhaps splitting this line multiple parts?
You can open files by file path. Just use
open('/path/to/file').Importing is only necessary for modules and packages – Python source code.
The only real notes here are to use
os.path.join()where joining paths for good compatibility across different operating systems and filesystems. The rest of theos.pathmodule is also worth a look wherever files are involved. Another common trap with windows paths is that using backslashes escape characters, so you must escape your backslashes ("some\\file") – an ugly option, use raw strings (r"some\file"), use forward slashes (Python will actually handle this automatically), or – the best option, pass your path as arguments to the aforementionedos.path.join().It may also be worth noting that using the
withstatement would improve your code.e.g:
Using
withensures your file gets closed – even if exceptions occur.