Issue
I have a script which generates multiple files after running the script. So i need all this files that is generated to be stored in to the directory created. and also if i run the script i need the the script to check if that directory already exist or not.
- if exist remove the previous contents in the directory and then only new contents should be stored in the directory.
eg: when i run script, Folder new
is first created and then files demo1.txt
and demo2.txt
which gets generated when i run the script is stored in to that directory. And if i run the script again i need all the first files created in that directory to be cleared.
This is my current attempt:
import os
if not os.path.exists("home/Documents/new"):
os.makedirs("home/Documents/new")
f = open("demo1.txt", "w")
f.write("welcome to python")
f.close()
f = open("demo2.txt", "w")
f.write("new world")
f.close()
but this will only create the directory. I'm not able to put the files to the directory
Solution
a) if the new directory doesn't exist, you need to change to it prior to create the files. b) if the new directory was created in a previous run, your files are never created in the current run (watch out for indentation!). Modifying a bit your script, this will always create the files in the new directory, whether it was already created in previous runs or not:
import os
newdir = "home/Documents/new"
if not os.path.exists(newdir):
os.makedirs(newdir)
olddir = os.getcwd()
os.chdir(newdir) # change execution to newdir
with open("demo1.txt", "w") as f:
f.write("welcome to python")
with open("demo2.txt", "w") as f:
f.write("new world")
os.chdir(olddir) # return to original dir
Answered By - Alberto Garcia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.