Create File In Sub Directory Python?
In my Python script, I need to create a new file in a sub directory without changing directories, and I need to continually edit that file from the current directory. My code: os.m
Solution 1:
Store the created directory in a variable. os.mkdir
throws if a directory exists by that name.
Use os.path.join
to join path components together (it knows about whether to use /
or \
).
import os.path
subdirectory = datetime + "-dst"
try:
os.mkdir(subdirectory)
except Exception:
pass
for ip in open("list.txt"):
with open(os.path.join(subdirectory, ip.strip() + ".txt"), "a") as ip_file:
...
Solution 2:
first convert the datetime to something the folder name can use something like this could work mydate_str = datetime.datetime.now().strftime("%m-%d-%Y")
then create the folder as required - check out Creating files and directories via Python Johnf
Post a Comment for "Create File In Sub Directory Python?"