I want to do the following in my program:
a) ask the user to type the name of a folder
b) create the folder in my directory
c) write files to this created folder
I've created the folder in my directory but I did not manage to write the text to a file and save it in this new folder. My strategy was to open for writing inserting the complete path of the directory + the variable that stores the name of the folder, but it did not work. Can anyone help me with that?
final_text=' '.join(l)
final_text=final_text.replace(' ,',',')
#print('\n\n', final_text)
def createFolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print('Error: Creating directory. '+ directory)
user2=input('\nWrite text to a file? Type "Y" for yes or "N" for no:')
if user2 =='Y':
text_name=input("name your folder. E.g. './texts/': ")
createFolder(text_name)
out_file=open('/Users/nataliaresende/Dropbox/PYTHON/'+text_name,"w")
out_file.write(final_text)
out_file.close()
print('\n\nText named',text_name, 'was written to a file. Check your directory')
else:
print('ok')
You can first create folder, then create file within that folder:
import os
user_input = input('\nWrite text to a file? Type "Y" for yes or "N" for no:')
if user_input == 'Y':
folder_name = input('name your folder. E.g. "texts": ')
folder = os.path.join('/Users/nataliaresende/Dropbox/PYTHON/', folder_name)
file_name = '{}.txt'.format(folder_name)
file = os.path.join(folder, file_name)
os.makedirs(folder)
with open(file, 'w') as f:
f.write('Some text')
print('\n\nText named "{}" was written to a file. Check your directory: {}'.format(file_name, folder))
else:
print('OK')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With