Issue
The file names.txt
contains a list of names. Each line contains one name.
Example:
- Lisa
- Luke
- Marry
I'm trying to:
Create a directory for each name in the list if it doesn't exist already.
Furthermore, in each of those directories create a file with the name
15.txt
.
with open("names.txt") as f:
for line in f:
readnewline = f.read()
name = []
for name in readnewline:
name = name.strip()
if '.' not in name[-1]:
directory = os.path.join(*([folder_path] + names))
if not os.path.exists(directory):
print('mk directory: {}'.format(directory))
os.makedirs(directory)
else:
new_file = os.path.join(*([folder_path] + names))
if not os.path.exists(new_file):
with open(new_file, 'w'):
print('write file: {}'.format(new_file))
Solution
os.path.exists("path\to\file")
checks if a path/file exists or not.
import os
with open("names.txt", "r") as fr:
names = fr.readlines()
fr.close()
names = [name.strip() for name in names]
# making directory for each name if not exist
for name in names:
if not os.path.exists(name):
os.makedirs(name)
# making a file in each directory
file_name = "15.txt" # file name
with open(os.path.join(name, file_name), "w") as fw:
fw.write("Some Data")
fw.close()
Answered By - Asadullah Naeem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.