Without needing to open a .csv file, I need to generate a new csv document. and when scheduled to be saved, it is hosted on a destination path defined by the user.
Without needing to open a .csv file, I need to generate a new csv document. and when scheduled to be saved, it is hosted on a destination path defined by the user.
Of course, open()
supports as a parameter a file name that can contain relative or absolute paths. For example, open("/home/manolo/miscosas/fichero.txt", "w")
.
The problem is if you want the code to work correctly on any platform, since in some the folder separator in a route is /
, while in others it is \
.
To make the code independent of the platform, you should use the tools that Python gives you in the module os.path
. The previous example would be:
import os.path
import os
nombre_fichero = os.path.join(os.sep, "home", "manolo", "miscosas", "fichero.txt")
f = open(nombre_fichero, "w")
You may also have problems if the route you are trying to write on does not exist. In that case you should create the appropriate subfolders, for which you can use os.makedirs()
Finally, there may be problems if the route you're trying to write on is protected and you do not have permissions, but that's another matter. All you can do in that case is capture the exception to issue an appropriate error message.